我有问题。我正在尝试测试广告组件的宽度,以验证广告位尺寸是否正确。
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
class MobileAdTestCase(StaticLiveServerTestCase):
def setUp(self):
# Create chrome browser with specific configuration
chrome_options = Options()
chrome_options.add_argument("--headless")
self.browser = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
self.browser.set_window_position(0, 0)
self.browser.set_window_size(320,568)
self.browser.implicitly_wait(10)
# Verify that browser has the specified size
browser_size = self.browser.get_window_size()
if browser_size['width'] != 320 or browser_size['height'] != 568:
self.fail("The browser didn't resize to the specified size.")
def tearDown(self):
self.browser.quit()
def test_ad_display(self):
# Given an url
url = "127.0.0.1:8080/ads"
# When visiting the page
self.browser.get(url)
# Assert that the ad has the right width
ad = self.browser.find_element_by_id("ad")
ad_width = ad.value_of_css_property('width')
ad_width = int(ad_width.replace('px', ''))
self.assertGreaterEqual(ad_width, 300)
当我运行python3 manage.py runserver
并输入测试中指定的url时,组件的宽度为300px,但是运行测试时的宽度为285px。最奇怪的是html(self.browser.find_element_by_tag_name('html')
)的宽度为305 px,但是当我在浏览器中打开chrome devtools时为320px(100%宽度)。
有人可以帮助我找出问题所在吗?谢谢!
编辑:
我发现问题是因为元素的宽度不是100%,所以如果我放置320px的浏览器大小,则元素不是100%。有谁知道为什么我必须强制html元素的宽度为100%?