6.3 On Implicit and Explicit Waits, and Voodoo time.sleeps

master
Jason Zhu 2020-11-09 16:58:56 +11:00
parent 80c26c12ed
commit 0e43a516aa
1 changed files with 35 additions and 1 deletions

View File

@ -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
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