Django 如何获得 live_server_url?

How Django get the live_server_url?

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

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

我也在读 TDD Python 这本书。我使用的是 Django 2.1,而不是 Django 1.11。 我遇到了与您描述的相同的问题。我发现在setUpClass()中,必须调用super().setUpClass()。

@classmethod
def setUpClass(cls):
    super().setUpClass()

与 tearDownClass() 类似。

我遇到了和你一样的问题。同样的例外。 所以真正的问题是我的主页url。我的主页 url 就像:http://127.0.0.1:8000/api/ 但服务器正在尝试使用 http://localhost:56458/.

self.browser.get(('%s%s' % (self.live_server_url, '/api/')))
from selenium import webdriver
from django.urls import reverse
import time

class TestApiPages(StaticLiveServerTestCase):
  
  def setUp(self):
      self.browser = webdriver.Chrome('functional_test/chromedriver.exe')
  
  def tearDown(self):
      self.browser.close()
  
  def test_api_list_displayed(self):
      self.browser.get(('%s%s' % (self.live_server_url, '/admin/')))