MahlerAdmirer
MahlerAdmirer

Reputation: 73

AssertionError when using variable instead of a literal

I am using Selenium WebDriver with Python. I have a code like the following. Why do I get an AssertionError, when I use assert <some variable> in driver.page_source? Instead of the variable if I use a literal, such as a string, the test passes.

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import sys
from instream import InStream
from outstream import OutStream
import stdio

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_search_in_python_org(self):
        driver = self.driver
        s = 'Ireland'
        driver.get("http://www.python.org")
        self.assertIn("Python", driver.title)
        elem = driver.find_element_by_name("q")
        elem.send_keys("pycon")
        elem.send_keys(Keys.RETURN)
        assert s in driver.page_source

    def tearDown(self):
        self.driver.close()       

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

Upvotes: 1

Views: 2168

Answers (1)

alecxe
alecxe

Reputation: 474161

This is a timing problem (reproduced it as well). The assertion is made at the moment the search results are not loaded yet and, hence, Ireland is not yet there in the page_source. Add a wait via WebDriverWait to make the test more reliable:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


driver = webdriver.Firefox()

s = 'Ireland'
driver.get("http://www.python.org")
wait = WebDriverWait(driver, 10)

elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)

# wait for results to be visible
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".list-recent-events li")))

assert s in driver.page_source

Note that .list-recent-events li is a CSS selector that matches the first event in the resulting event list.

Upvotes: 3

Related Questions