Skip to content

Commit

Permalink
refactor: improve code in test_network_config
Browse files Browse the repository at this point in the history
  • Loading branch information
piglei committed Oct 25, 2024
1 parent f067499 commit ee20f8e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
2 changes: 1 addition & 1 deletion apiserver/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ $ pytest --reuse-db -s --maxfail=1 ./tests/

API 测试,指通过请求接口并验证响应是否符合预期的自动化测试。同单元测试相比,API 测试的速度通常更慢、依赖项更多,但是能覆盖更多的业务逻辑。

本项目的 API 测试代码主要位于 [./paasng/tests/api/](./paasng/tests/api/) 目录下。同传统的“黑盒 API 测试”(发送真实 HTTP 请求)有所不同,本项目的 API 测试是基于 Django/DRF 框架的 API 测试套件编写,并不发出真实网络请求,不过,这并不影响最终的测试效果。
本项目的 API 测试代码主要位于 [./paasng/tests/api/](./paasng/tests/api/) 目录下。与传统的“黑盒 API 测试”(发送真实 HTTP 请求)有所不同,本项目的 API 测试是基于 Django/DRF 框架的 API 测试套件编写,并不发出真实网络请求,不过,这并不影响最终的测试效果。

一个典型的 API 测试,由“数据准备”、“发送请求”、“验证响应”这三个步骤组成。为了提升测试效果,让代码尽可能地便于维护,编码时请遵循以下建议:

Expand Down
12 changes: 6 additions & 6 deletions apiserver/paasng/tests/api/bkapp_model/test_network_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,15 @@ def test_get(self, with_default_res, api_client, bk_app, test_url):
],
)
def test_upsert(self, with_default_res, api_client, test_url, req_body):
old_ns = with_default_res.data["nameservers"]
old_ha = with_default_res.data["host_aliases"]

response = api_client.post(test_url, req_body)

assert response.status_code == 200
# When the field is missing in the body, the old value should be kept
assert response.data["nameservers"] == req_body.get("nameservers") or old_ns
assert response.data["host_aliases"] == req_body.get("host_aliases") or old_ha

# The value of a field should has been updated when it's provided in the request
# body, otherwise it should be the same as before.
expected = with_default_res.data.copy()
expected.update(req_body)
assert response.data == expected

def test_upsert_no_data(self, with_default_res, api_client, test_url):
response = api_client.post(test_url)
Expand Down

0 comments on commit ee20f8e

Please sign in to comment.