From 0e43a516aa43617158ec9cf03525d888c0885e7a Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Mon, 9 Nov 2020 16:58:56 +1100 Subject: [PATCH] 6.3 On Implicit and Explicit Waits, and Voodoo time.sleeps --- textbook/chap6.md | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/textbook/chap6.md b/textbook/chap6.md index dd5e796..f0349e2 100644 --- a/textbook/chap6.md +++ b/textbook/chap6.md @@ -45,4 +45,38 @@ python manage.py test lists Sometimes, mismatch between firefox and (Selenium + Geckodriver) may result failure in test, as firefox may auto upgrade itself at night. Upgrade Selenium + Geckodriver as follow: 1. `pip install --upgrade selenium` -2. Download new geckodriver \ No newline at end of file +2. Download new geckodriver + +## 6.3 On Implicit and Explicit Waits, and Voodoo time.sleeps + +Implicit Waits & Explicit Waits: +* Implicit Waits: Selenium tries to wait "automatically" for you when it thinks the page is loading. But it's unstable, DON'T USE IT. +* Explicit Waits: `time.sleep(...)` in FT. It's hard to set a fixed second (Voodoo Sleep). A while loop with try/except will be more better + +```python +from selenium.common.exceptions import WebDriverException + +MAX_WAIT = 10 # Maximum amount of time we're prepared to wait +[...] + + def wait_for_row_in_list_table(self, row_text): + start_time = time.time() + while True: + try: + table = self.browser.find_element_by_id('id_list_table') + rows = table.find_elements_by_tag_name('tr') + self.assertIn(row_text, [row.text for row in rows]) + return + except (AssertionError, WebDriverException) as e: + if time.time() - start_time > MAX_WAIT: + raise e + time.sleep(0.5) +``` + +Replace all `check_for_row_in_list_table` with `wait_for_row_in_list_table` + +### "BEST PRACTICES" Applied in this Chapter + +* Ensuring test isolation and managing global state +* Avoid "voodoo" sleeps (i.e. `time.sleep`) +* Don't rely on Selenium's implicit waits \ No newline at end of file