python - Django 如何获取 live_server_url?

标签 python django port netstat

我从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
======================================================================
...

我的功能测试/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

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

关于python - Django 如何获取 live_server_url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041841/

相关文章:

Django 使用 kwarg 重定向

python - 建立新连接失败: [Errno -2] Name or service not known

c - 如何使用相同的 UDP 套接字发送和接收数据包?我在这段代码中缺少什么?

python - 不支持 hdf5(请安装/重新安装 h5py)不支持 Scipy!什么时候导入 TFLearn?

python - 如何在 PyQt4 中滚动显示 RGBA numpy 数组图像?

python - 如何在不增加OpenCV大小的情况下将视频分解为帧

python - Django==2.1.4 - 博客

python - 如何使用 Ajax 将 Fabric 任务结果从 Django 流式传输到 stdout

Hadoop端口50070在使用Windows安装错误

python - Altair/Vega-Lite 条形图 : filter top K bars from aggregated field