使用Django 1.11从Docker Selenium运行LiveServerTestCase
由于Django 1.11 ,选项--liveserver
已从manage.py test
命令中删除。
我正在使用这个选项来允许liveserver通过以下命令从机器的IP地址而不是localhost
:
./manage.py test --liveserver=0.0.0.0:8000
不幸的是,这个选项已经不存在了,我正在寻找一个新的解决scheme来允许我的Docker Selenium映像在testing期间访问我的LiveServerTestCase。
我通过重写StaticLiveServerTestCase
和更改host
属性来find解决scheme。
例:
import socket from django.contrib.staticfiles.testing import StaticLiveServerTestCase class SeleniumTestCase(StaticLiveServerTestCase): @classmethod def setUpClass(cls): cls.host = socket.gethostbyname(socket.gethostname()) super(SeleniumTestCase, cls).setUpClass()
有了这个解决scheme,我的机器的IP被赋予了LiverServerTestCase的LiverServerTestCase
因为默认值是localhost
。
所以现在我的liveserver可以在我的本地主机之外通过使用IP ..
有了这个线程和VivienCormier的帮助,Django 1.11和docker-compose
version: '2' services: db: restart: "no" image: postgres:9.6 ports: - "5432:5432" volumes: - ./postgres-data:/var/lib/postgresql/data env_file: - .db_env web: build: ./myproject command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - ./myproject:/usr/src/app depends_on: - db - selenium env_file: .web_env selenium: image: selenium/standalone-firefox expose: - "4444"
import os from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class TestHomePageView(StaticLiveServerTestCase): @classmethod def setUpClass(cls): cls.host = 'web' cls.selenium = webdriver.Remote( command_executor=os.environ['SELENIUM_HOST'], desired_capabilities=DesiredCapabilities.FIREFOX, ) super(TestHomePageView, cls).setUpClass() @classmethod def tearDownClass(cls): cls.selenium.quit() super(TestHomePageView, cls).tearDownClass() def test_root_url_resolves_to_home_page_view(self): response = self.client.get('/') self.assertEqual(response.resolver_match.func.__name__, LoginView.as_view().__name__) def test_page_title(self): self.selenium.get('%s' % self.live_server_url) page_title = self.selenium.find_element_by_tag_name('title').text self.assertEqual('MyProject', page_title)
.web_env文件
SELENIUM_HOST=http://selenium:4444/wd/hub
使用StaticLiveServerTestCase
似乎不是必要的:相同的方法适用于其父类:
class End2End(LiveServerTestCase): host = '0.0.0.0' # or socket.gethostbyname(...) like @VivienCormier did