Location>code7788 >text

jenkins dynamically switch environments

Popularity:970 ℃/2024-08-31 12:19:30

I. Code layer implementation of dynamic switching

1. First declare the pytest_addoption hook function under, write it as follows

def pytest_addoption(parser):
    # Set the command line parameters to be received
    ("--env", default="prod", choices=['pre', 'uat', 'prod', 'test'],
                     help="Command line parameter, --env sets environment switching")

--env: command line arguments

default: if --env is not passed at startup, the default value is prod

choices: range of parameter values

help: command line instructions, can be viewed by running: pytest --help in the terminal

file to create a configuration file, written as follows

[HOST]
pre=https://pre-
prod=http://
uat=https://uat-
test=

Here different environments correspond to different addresses

Creating basecase wrappers to read ini files

def read_ini(config_path):
    with open(config_path, mode='r') as f:
        dict_ini = {().split('=')[0]: ().split('=')[1] for i in ()[1:]}
        return dict_ini

config_path is the ini address and return returns the processed data in dict format.

4. Use case layer call method to get different environment address

from  import read_ini
from common.headle_path import config_path


# @(1)
def test_login(request,webdriver_init):
    custom_arg = ("--env")
    webdriver_init.get(read_ini(config_path)[custom_arg])

request: fixed write, pass ('--env') to get the arguments passed at startup

webdriver_init: firmware function to initialize webdriver in conftest

Start the use case in the

import pytest

if __name__ == '__main__':
    (['-s', '-v', '--env=prod'])

II.jenkins to achieve dynamic switching

The basic configuration can be found at: /lihongtaoya/p/18351371

1.existjobSelect under Configuration:This project is parameterized

Fill in the name, options, and description

Fill in the Win run command under Windows batch command

%env%: indicates that a value is passed to the code when the python script is run. env is the name set under This project is parameterized.

3. How to get this value

In python you can get it from the argv list in the os module, written as follows

import sys

import pytest

if __name__ == '__main__':
    # (['-s', '-v', '--env=prod'])
    arg_one = [1]
    (['-s', '-v', f'--env={arg_one}'])

[1]: indicates that a value passed is obtained

4. Start building

In the build options you can see the environment options we have set and a description, select an environment and start building.