In actual work, in order to facilitate maintenance, the switching and configuration of the environment are usually not completed in a hard-coded form. This article will reconstruct this part and use a data-driven approach to complete the configuration of multiple environments.
Environmental preparation
The environment configuration part is changed to data-driven mode:
code show as below:
#把host修改为ip,并附加host header
env={
"docker.testing-studio.com": {
"dev": "127.0.0.1",
"test": "1.1.1.2"
},
"default": "dev"
}
data["url"]=str(data["url"]).replace(
"docker.testing-studio.com",
env["docker.testing-studio.com"][env["default"]]
)
data["headers"]["Host"]="docker.testing-studio.com"
Actual demonstration
Still taking YAML as an example, put all the environment configuration information in the env.yml
file. If you are afraid of making mistakes, you can first yaml.safe_dump(env)
convert the code in dict format to YAML.
As shown below, what is printed out is the configuration information successfully converted into YAML format:
def test_send(self):
env={
"docker.testing-studio.com": {
"dev": "127.0.0.1",
"test": "1.1.1.2"
},
"default": "dev"
}
yaml2 = yaml.safe_dump(env)
print("")
print(yaml2)
Paste the printed content into the env.yml
file:
docker.testing-studio.com:
dev: "127.0.0.1"
test: "1.1.1.2"
level: 4
default:
"dev"
The code in the environment preparation is slightly modified, and the env
variables are changed from a typical dict to use yaml.safe_load
read env.yml
:
# 把host修改为ip,并附加host header
env = yaml.safe_load(open("./env.yml"))
data["url"] = str(data["url"]).\
replace("docker.testing-studio.com",
env["docker.testing-studio.com"][env["default"]])
data["headers"]["Host"] = "docker.testing-studio.com"
In this way, you can use a data-driven approach env.yml
to directly modify configuration information by modifying files.
Ask a day
Regarding the data-driven testing, have you encountered any problems that impressed you, or practical experience that you can share? Please leave a message in the comment area.
For more advanced content of the interface testing framework, we will share in the follow-up article. Pay attention to the " Programmer Two Black " official account to get more test and development dry goods content.