如何在pythonDjango模型中进行单元或集成测试

2024-04-19 05:48:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在YouTube https://www.youtube.com/watch?v=6wxO8hRIP4w上看了这个教程,它在某种程度上帮助了我,但教程缺少关于如何测试Django模型的内容。你知道吗

以下是我目前掌握的代码:

你知道吗确认测试.py你知道吗

import pytest
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
import requests

@pytest.fixture(name="homepage")
def fixture_homepage(function_scoped_container_getter) -> str:
    service = function_scoped_container_getter.get('app').network_info[1]
    base_url = f"http://{service.hostname}:{service.host_port}"

    retry = Retry(
        total = 30,
        backoff_factor=10,
        status_forcelist = [500, 502, 503, 504]
    )

    session = requests.Session()
    session.mount('http://', HTTPAdapter(max_retries=retry))

    return base_url

第一_测试.py你知道吗

from requests import get

pytest_plugins = ["docker_compose"]

def test_one():
    assert 1==1

def test_initial_ticket(homepage: str):
    print("HOMEPAGE: ", homepage)
    temp_str = get(homepage+"/admin").text

    #check if the pytest can already open the admin login page
    assert "Admin Login" in temp_str

当我运行pytest integration_tests/initial_user_receipt_test.py -s时,首先_测试.py通行证。我还可以看到,当我运行这个脚本时,docker映像被构建。你知道吗

但是,我想测试插入到型号.py与集成测试文件夹位于同一文件夹中。我尝试过直接导入模型和模型中的一些类,但是没有成功。你知道吗

我的文件夹结构如下:

- Project
   - integration_tests
      - conftest.py
      - first_test.py
   - apps.py
   - models.py #contains a User class

Tags: frompy模型testimport文件夹getpytest