在Selenium中使用webdriver进行测试时,如何加载整个Django项目(包括js文件)?

s4n0splo  于 2023-01-17  发布在  Go
关注(0)|答案(2)|浏览(99)

我正在使用Selenium来测试我的Django项目的JavaScript。
Web驱动程序正在获取index.html,这是主页,但JavaScript没有加载到我的index.html页面中(就好像我正在运行整个项目,而不是单个页面/模板)。
我如何加载整个Django项目以使Web驱动程序获得预期的结果?
我运行了测试文件,并得到了以下错误:
“self.assertEqual(驱动程序.查找元素(按.ID,“现金表-美元”).文本,100)Assert错误:'{{美元|整数逗号}}'!= 100”
{{美元|intcomma }}是模板化的,因为我相信Django项目中的其他文件没有加载。
我希望它最初是0,然后在测试中单击按钮后变为100。

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

def file_uri(filename):
    return pathlib.Path(os.path.abspath(filename)).as_uri()

driver = webdriver.Chrome(ChromeDriverManager().install())

class ClientSideTests(unittest.TestCase):

    def test_deposit_withdraw(self):
        driver.get(file_uri("portfolio/templates/portfolio/index.html"))
        balance = driver.find_element(By.ID, "cash-table-usd").text
        driver.find_element(By.ID, "cash-amount").send_keys(100)
        cash_submit = driver.find_element(By.ID, "cash-button")
        cash_submit.click()
        self.assertEqual(driver.find_element(By.ID, "cash-table-usd").text, 100)

if __name__ == "__main__":
    unittest.main()
ux6nzvsh

ux6nzvsh1#

cd到您的项目目录中,然后

python manage.py runserver
8i9zcol2

8i9zcol22#

你应该使用Django的StaticLiveServerTestCase,下面是运行Selenium测试文档中LiveServerTestCase部分的一个例子。

class MySeleniumTests(StaticLiveServerTestCase):
    fixtures = ['user-data.json']

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.selenium = WebDriver()
        cls.selenium.implicitly_wait(10)

    @classmethod
    def tearDownClass(cls):
        cls.selenium.quit()
        super().tearDownClass()

    def test_login(self):
        self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
        username_input = self.selenium.find_element(By.NAME, "username")
        username_input.send_keys('myuser')
        password_input = self.selenium.find_element(By.NAME, "password")
        password_input.send_keys('secret')
        self.selenium.find_element(By.XPATH, '//input[@value="Log in"]').click()

相关问题