Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do find_elements_by_* functions always reflect DOM order?

Does a call like browser.find_elements_by_css_selector('input[type=text]') always return WebElement objects in the order that reflects the DOM?

I ask because I have a to-do list-like application and the order that form elements appear on the page (added dynamically) is vital, and perhaps I'm being anal but I'm testing this behaviour as part of my test suite.

N.B.: I'll likely run the test in a variety of browsers.

My test (Python with unittest):

def test_titles_should_appear_in_the_order_they_are_entered(self):
    titles = ['title 1', 'title 2', 'title 3']
    for title in titles:
        self._type_new_title(title).send_keys(Keys.RETURN)
    inputs = self.browser.find_elements_by_css_selector('input[type=text].title')
    # assumption: inputs will always reflect the DOM order, top to bottom
    input_vals = [i.get_attribute('value') for i in inputs]
    self.assertEqual(input_vals, titles)
like image 777
KnewB Avatar asked Nov 12 '22 18:11

KnewB


1 Answers

In my experience this is true, which also makes sense, in that the FindElements methods are going to parse the document looking for matches based on the locator.

Additionally, even if they aren't exactly in the DOM order, it will be consistent each time, so you should be safe to write your test accordingly.

However, keep in mind that anytime you use order on multiple matches, that if you add or remove inputs, then that order is likely to change, and you'll need to update the test accordingly.

like image 199
Nathan Dace Avatar answered Nov 14 '22 22:11

Nathan Dace