Selenium 测试适用于生产但不适用于开发

时间:2021-07-08 08:39:55

标签: python selenium vue.js selenium-chromedriver

我有一个 Vue.js 应用程序,我想为其编写 selenium 测试。当我针对已部署的应用生产版本运行测试时,测试通过,但在针对本地版本运行时失败。

当然,在本地运行时,Vue.js 应用不是从构建运行,而是使用 npm run serve 运行。

我在本地进行了以下 docker compose 设置:

  app:
    build:
      context: .
      dockerfile: ./app.dockerfile
    image: app
    command: npm run serve
    ports:
      - 8080:8080
    volumes:
      - ./app:/app

  selenium:
    image: selenium/standalone-chrome:91.0
    depends_on:
      - app

  e2e-tests:
    build:
      context: .
      dockerfile: ./e2e_tests.dockerfile
    image: e2e-tests
    command: poetry run python ./foo.py
    depends_on:
      - app
      - selenium
    volumes:
      - ./e2e_tests:/app

以下是使用 e2e-testsselenium 容器在互联网上测试已部署的应用生产版本的基本测试:

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--window-size=1420,1080")
chrome_options.add_argument("--headless")
driver = webdriver.Remote("http://selenium:4444/wd/hub", options=chrome_options)

driver.get('https://www.example.com')

try:
    assert 'My app title' in driver.title
except AssertionError:
    print('invalid title')

driver.quit()

如果我现在将上述测试更改为使用 app 容器,它只是 Vue 应用程序的本地运行版本,它会失败,因为标题为空:

driver.get('http://app:8080')

我尝试在 wait 之后的测试中添加 10 秒 driver.get,但标题仍然为空。

1 个答案:

答案 0 :(得分:0)

事实证明,即使我可以通过浏览器访问应用程序,当 selenium 尝试从 docker 中调用它时,应用程序也返回了 Invalid Host Header。一定是一些 docker 相关的特质。

解决方案是按如下方式更新我的 vue.config.js

module.exports = {
  devServer: {
    disableHostCheck: true
  }
};

disableHostCheck 解决了这个问题。显然这应该只在开发中使用,因为如果在生产中启用它会存在安全风险。