使用Django 1.11从Docker Selenium运行LiveServerTestCase

时间:2017-05-29 10:22:45

标签: python django selenium docker django-1.11

Since Django 1.11,选项--liveserver已从manage.py test命令中删除。

我使用此选项允许使用以下命令从机器的IP地址而不是localhost访问liveserver:

./manage.py test --liveserver=0.0.0.0:8000

不幸的是,这个选项已经消失,我正在寻找一种新的解决方案,允许我的Docker Selenium映像在测试期间访问我的LiveServerTestCase。

3 个答案:

答案 0 :(得分:3)

我通过覆盖StaticLiveServerTestCase和更改host属性找到了解决方案。

示例:

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()

使用此解决方案,我的计算机的IP将提供给LiverServerTestCase的{​​{3}},因为setUpClasslocalhost

所以现在我的liveserver可以在我的localhost外部使用IP ..

答案 1 :(得分:0)

this thread和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

答案 2 :(得分:0)

使用StaticLiveServerTestCase似乎没有必要:同样的方法适用于其父类:

class End2End(LiveServerTestCase):  
    host = '0.0.0.0'  # or socket.gethostbyname(...) like @VivienCormier did