Skip to main content
 首页 » 编程设计

python之Django 如何获取 live_server_url

2024年09月07日44birdshome

我从 TDD with Python 学习了 Django 功能测试并适应我的项目。

我的FT很简单,看url的标题

我使用 live_server_url 通过 selenium 进行测试。 但它转到另一个端口号(56458),而不是 8000。 (我看书的时候不是)

$ python manage.py runserver & 
... 
Starting development server at http://127.0.0.1:8000/ 
... 
$ python manage.py test functional_test 
... 
http://localhost:56458 
E 
====================================================================== 
... 

我的 functional_tests/tests.py 是:

from django.test import LiveServerTestCase 
 
from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
from selenium.common.exceptions import WebDriverException 
 
from time import time, sleep 
 
 
class NewVistorTest(LiveServerTestCase): 
 
    def setUp(self): 
        self.browser = webdriver.Firefox() 
        self.browser.implicitly_wait(3) 
 
 
    def tearDown(self): 
        self.browser.quit() 
 
    def test_render_a_list_of_candiates_in_home(self): 
        self.browser.get(self.live_server_url) 
        h1_text = self.browser.find_element_by_tag_name('h1').text 
 
        self.assertEqual(self.browser.title, 'Voting Dapp') 
        self.assertEqual(h1_text, 'A Simple Voting Application') 

Doc说:

The live server listens on localhost and binds to port 0 which uses a free port assigned by the operating system. The server’s URL can be accessed with self.live_server_url during the tests.

所以我尝试查看监听端口(我认为我对这部分还不成熟):

$ netstat | grep LISTEN 
$ # nothing printed! 

请您参考如下方法:

您使用 LiveServerTestCase。它会为您启动一个 Django 服务器。无需像上一章那样启动服务器。

LiveServerTestCase does basically the same as TransactionTestCase with one extra feature: it launches a live Django server in the background on setup, and shuts it down on teardown. This allows the use of automated test clients other than the Django dummy client such as, for example, the Selenium client, to execute a series of functional tests inside a browser and simulate a real user’s actions.

https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.LiveServerTestCase

因此,您的测试服务器应该有一些不同于开发服务器的端口。此外,测试服务器是一个带有空数据库的空项目。因此,您的测试需要在执行实际测试用例之前创建所需的内容。

或者,您可以使用 --liveserver LIVESERVER 将测试指向其他环境。参见 python manage.py test -h。

我认为针对开发服务器进行测试是错误的,因为此数据可以更改(手动和以前的测试),因此不可重现。我相信测试应该是完全自包含的,这样它就可以单独运行,也可以与任意数量的其他测试用例任意组合运行。