• 自动化脚本如何切换环境?Pytest这些功能你必须要掌握


    在这里插入图片描述


    一、前言

    测试工程师每天都跟不同的环境打交道,比如线上环境,测试环境,预上线环境等等,那么作为自动化测试人员写的代码,我们也要具备能自由切换环境的能力,如何能让我们python语言写的测试用例可以自由切换到不同的环境下面去运行呢?

    二、安装

    pytest有一个插件叫pytest-base-url ,是管理base_url非常好的一款插件

    pip install pytest-base-url
    
    • 1

    三、使用

    第1种:使用方式是终端添加–base-url这个命令

    pytest --base-url http://www.baidu.com works
    
    • 1
    #encoding=utf-8
    import time
    import requests
    import pytest
    
    name = "登录"
    @pytest.fixture(scope="class")
    def class_setup_teardown():
        print(f"\n============= {name} 接口测试开始! ==============")
        yield
        print(f"\n============= {name} 接口测试结束! ==============")
    
    
    @pytest.mark.usefixtures("class_setup_teardown")
    class TestWork:
    
        def test_work1(self,base_url):
            resp=requests.get(base_url)
            print(base_url)
            resp_code=resp.status_code
            assert resp_code==200
    
    if __name__ == '__main__':
        pytest.main()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    执行结果:
    在这里插入图片描述

    第2种:使用方式是在pytest.ini配置文件种去配置base_url,然后自动读取url的数据,这样就不用添加–base-url这个命令行参数了:

    在这里插入图片描述

    #encoding=utf-8
    import time
    import requests
    import pytest
    
    name = "登录"
    @pytest.fixture(scope="class")
    def class_setup_teardown():
        print(f"\n============= {name} 接口测试开始! ==============")
        yield
        print(f"\n============= {name} 接口测试结束! ==============")
    
    
    @pytest.mark.usefixtures("class_setup_teardown")
    class TestWork:
    
        def test_work1(self,base_url):
            resp=requests.get(base_url)
            print(base_url)
            resp_code=resp.status_code
            assert resp_code==200
    
    
    if __name__ == '__main__':
        pytest.main()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    运行命令:

    pytest works
    
    • 1

    第3种:pytest有个hooks函数,可以自定义命令行参数,一般在conftest.py中去引用。

    conftest.py中写pytest_addoption这个hooks函数,可以自定义命令行参数,base_url只能对一个url地址进行传递,那么有的项目不仅需要多项目请求的url地址进行不同环境的切换,还需要对mysql的url地址进行不同的切换,这个时候就可以用自定义命令,定义不同的命令行参数,这样我们在执行pytest的时候就可以自由进行传递。

    conftest.py

    import pytest
    @pytest.fixture(scope='session',autouse=True)
    def my1_fixture():
        print('----这是前置方法----')
        yield
        print('----这是后置方法----')
    
    
    
    def pytest_addoption(parser):
        parser.addoption( "--test-url",
                          action="store",
                          default="http://www.baidu.com",
                          help="传递项目url"
        )
    
        parser.addoption("--produce-url",
                         action="store",
                         default="http://www.sogou.com",
                         help="传递数据库主机名称"
                         )
    
        parser.addoption("--develop-url",
                         action="store",
                         default="https://www.tencent.com/",
                         help="传递数据库主机名称"
                         )
    
    # 获取 pytest.ini 配置参数
    @pytest.fixture(scope="session")
    def get_url(request):
        test_url = request.config.getoption('--test-url')
        produce_url = request.config.getoption('--produce-url')
        develop_url = request.config.getoption('--develop-url')
        print("\n读取到配置文件的测试url地址:%s" % test_url)
        print("\n读取到配置文件的生产url地址:%s" % produce_url)
        print("\n读取到配置文件的开发url地址:%s" % develop_url)
        return test_url,produce_url,develop_url
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    test_work.py

    #encoding=utf-8
    import time
    import requests
    import pytest
    
    name = "登录"
    @pytest.fixture(scope="class")
    def class_setup_teardown():
        print(f"\n============= {name} 接口测试开始! ==============")
        yield
        print(f"\n============= {name} 接口测试结束! ==============")
    
    
    @pytest.mark.usefixtures("class_setup_teardown")
    class TestWork:
    
        def test_work1(self,get_url):
            resp=requests.get(get_url[0])
            print(get_url[1])
            resp_code=resp.status_code
            assert resp_code==200
    
    
    if __name__ == '__main__':
        pytest.main()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    在这里插入图片描述

    第4种:通过yml文件和fixture进行配合使用

    如果需要改环境,直接在con.yml中改参数即可(develop\test\produce)

    在这里插入图片描述

    conftest.py

    import pytest
    import yaml
    
    
    @pytest.fixture(scope='session',autouse=True)
    def my1_fixture():
        print('----这是前置方法----')
        yield
        print('----这是后置方法----')
    
    @pytest.fixture(scope="session")
    def config():
        with open(r'D:\project_development\api_pytest\conf.yml',"r",encoding="utf-8") as f:
            conf=yaml.load(f,Loader=yaml.FullLoader)
            return conf
    
    @pytest.fixture(scope="session")
    def env_vars(config):
        env=config["env"]
        mapping={
            "test":{
                "base_url":"http://www.baidu.com",
                "mysql_url":"127.0.0.1",
            },
            "develop": {
                "base_url": "http://www.sogou.com",
                "mysql_url": "127.0.0.2",
            },
            "produce": {
                "base_url": "http://www.tencent.com",
                "mysql_url": "127.0.0.3",
            },
        }
        base_url=mapping[env]['base_url']
        mysql_url=mapping[env]['mysql_url']
        return base_url,mysql_url
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    test_work.py

    #encoding=utf-8
    import time
    import requests
    import pytest
    
    name = "登录"
    @pytest.fixture(scope="class")
    def class_setup_teardown():
        print(f"\n============= {name} 接口测试开始! ==============")
        yield
        print(f"\n============= {name} 接口测试结束! ==============")
    
    
    @pytest.mark.usefixtures("class_setup_teardown")
    class TestWork:
    
        def test_work1(self,env_vars):
            resp=requests.get(env_vars[0])
            print(env_vars[0])
            print(env_vars[1])
            resp_code=resp.status_code
            assert resp_code==200
    
    
    if __name__ == '__main__':
        pytest.main()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    在这里插入图片描述

  • 相关阅读:
    阿里云天池大赛赛题(机器学习)——工业蒸汽量预测(完整代码)
    ChatGPT Vision初体验
    C++语法基础(1)——编程入门
    iOS学习:isKindOfClass & isMemberOfClass
    数据结构和算法之图
    通过python搭建文件传输服务器;支持多台电脑之间互相传输文件(支持局域网或广域网)(应该也能用于虚拟机和宿主机之间)
    MongoDB导入导出备份数据
    Hadoop 分布式集群搭建教程(2023在校生踩坑版)
    P2607 [ZJOI2008] 骑士
    ES升级--04--SpringBoot整合Elasticsearch
  • 原文地址:https://blog.csdn.net/YZL40514131/article/details/127951325