Bird
Raised Fist0
Selenium Pythontesting~20 mins

Retry mechanism for flaky tests in Selenium Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Retry Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this retry decorator on flaky test?
Consider this Python code using Selenium and a retry decorator for flaky tests. What will be printed when the test function is run?
Selenium Python
import random

def retry(times):
    def decorator(func):
        def wrapper():
            for attempt in range(1, times + 1):
                try:
                    func()
                    print(f"Test passed on attempt {attempt}")
                    break
                except Exception as e:
                    print(f"Attempt {attempt} failed: {e}")
                    if attempt == times:
                        print("Test failed after retries")
        return wrapper
    return decorator

@retry(3)
def flaky_test():
    if random.choice([True, False]):
        raise Exception("Random failure")

flaky_test()
ATest passed on attempt 3
BAttempt 1 failed: Random failure\nTest passed on attempt 2
CTest passed on attempt 1
DAttempt 1 failed: Random failure\nAttempt 2 failed: Random failure\nAttempt 3 failed: Random failure\nTest failed after retries
Attempts:
2 left
💡 Hint
The test stops retrying once it passes.
❓ assertion
intermediate
1:30remaining
Which assertion correctly verifies retry count in flaky test?
You want to assert that a flaky Selenium test retried exactly 3 times before failing. Which assertion code snippet correctly checks this?
Selenium Python
retry_attempts = []

def flaky_test():
    retry_attempts.append(1)
    raise Exception("Fail")

# Retry decorator calls flaky_test 3 times

# Which assertion below is correct?
Aassert retry_attempts == 3
Bassert len(retry_attempts) == 3
Cassert retry_attempts.count == 3
Dassert retry_attempts.length == 3
Attempts:
2 left
💡 Hint
retry_attempts is a list, check its length.
🔧 Debug
advanced
2:30remaining
Why does this retry decorator not retry on failure?
This retry decorator is supposed to retry a flaky Selenium test 3 times, but it only runs once. What is the bug?
Selenium Python
def retry(times):
    def decorator(func):
        def wrapper():
            for attempt in range(times):
                try:
                    func()
                    print(f"Passed on attempt {attempt}")
                    return
                except Exception:
                    print(f"Failed on attempt {attempt}")
        return wrapper
    return decorator

@retry(3)
def flaky_test():
    raise Exception("Fail")

flaky_test()
AThe decorator is missing @functools.wraps
BThe range(times) should start at 1, not 0
CThe exception is not caught properly
DThe 'return' inside try block stops retries after first attempt
Attempts:
2 left
💡 Hint
Check what happens when the test passes or fails inside the loop.
❓ framework
advanced
1:30remaining
Which pytest feature best supports retrying flaky Selenium tests?
You want to automatically retry flaky Selenium tests in pytest without writing custom decorators. Which pytest feature or plugin should you use?
Apytest-rerunfailures plugin
Bpytest-mock plugin
Cpytest-cov plugin
Dpytest-xdist plugin
Attempts:
2 left
💡 Hint
Look for a plugin that reruns failed tests.
🧠 Conceptual
expert
2:00remaining
What is the main risk of using retry mechanisms for flaky Selenium tests?
Retrying flaky Selenium tests can hide underlying problems. What is the biggest risk of relying heavily on retries?
AMasking real issues and reducing test suite reliability
BIncreasing test execution speed significantly
CMaking tests easier to maintain and debug
DGuaranteeing 100% test pass rate
Attempts:
2 left
💡 Hint
Think about what happens if flaky tests are ignored by retries.

Practice

(1/5)
1. What is the main purpose of a retry mechanism in Selenium tests?
easy
A. To permanently ignore failed tests without rerunning
B. To speed up test execution by running tests in parallel
C. To rerun tests that fail due to temporary issues like slow loading
D. To generate detailed logs for every test step

Solution

  1. Step 1: Understand flaky tests

    Flaky tests fail sometimes due to temporary problems like slow page loads or network delays.
  2. Step 2: Purpose of retry mechanism

    Retry mechanism reruns failed tests to check if failure was temporary, reducing false failures.
  3. Final Answer:

    To rerun tests that fail due to temporary issues like slow loading -> Option C
  4. Quick Check:

    Retry mechanism = rerun flaky tests [OK]
Hint: Retry fixes temporary failures by rerunning tests [OK]
Common Mistakes:
  • Thinking retry speeds up tests
  • Assuming retry ignores failures
  • Confusing retry with logging
2. Which of the following is the correct way to implement a simple retry decorator in Python for Selenium tests?
easy
A. def retry(func): try: func() except Exception: func()
B. def retry(func): def wrapper(): for _ in range(3): try: return func() except Exception: pass return wrapper
C. def retry(func): while True: func() return func
D. def retry(func): for _ in range(3): func() return func

Solution

  1. Step 1: Check retry decorator structure

    def retry(func): def wrapper(): for _ in range(3): try: return func() except Exception: pass return wrapper defines a wrapper function that tries to run the test 3 times catching exceptions.
  2. Step 2: Verify retry logic correctness

    def retry(func): def wrapper(): for _ in range(3): try: return func() except Exception: pass return wrapper retries on exception and returns on success, which is correct retry behavior.
  3. Final Answer:

    def retry(func): def wrapper(): for _ in range(3): try: return func() except Exception: pass return wrapper -> Option B
  4. Quick Check:

    Retry decorator = try 3 times with exception catch [OK]
Hint: Retry decorator wraps function with try-except loop [OK]
Common Mistakes:
  • Not catching exceptions inside loop
  • Infinite loops without exit
  • Calling function multiple times without try-except
3. Given this retry decorator and test function, what will be printed?
def retry(func):
    def wrapper():
        for i in range(2):
            try:
                return func()
            except Exception:
                print(f"Retry {i+1} failed")
        print("All retries failed")
    return wrapper

@retry
def test():
    print("Running test")
    raise Exception("Fail")

test()
medium
A. Running test Retry 1 failed Running test Retry 2 failed All retries failed
B. Running test All retries failed
C. Running test Retry 1 failed Retry 2 failed
D. Running test Retry 1 failed Running test Retry 2 failed

Solution

  1. Step 1: Analyze retry loop

    The wrapper tries to run test twice. Each time test() prints "Running test" then raises Exception.
  2. Step 2: Trace output

    On first try, prints "Running test", then exception triggers "Retry 1 failed". Second try repeats same steps, then prints "Retry 2 failed". After loop ends, prints "All retries failed".
  3. Final Answer:

    Running test Retry 1 failed Running test Retry 2 failed All retries failed -> Option A
  4. Quick Check:

    Retry prints on each failure, then final failure message [OK]
Hint: Each retry prints failure message, then final failure after loop [OK]
Common Mistakes:
  • Missing repeated 'Running test' print
  • Ignoring final 'All retries failed' print
  • Assuming retry stops after first failure
4. You wrote this retry decorator but it does not retry on failure. What is the bug?
def retry(func):
    def wrapper():
        for _ in range(3):
            try:
                func()
            except Exception:
                continue
    return wrapper
medium
A. The decorator is missing the @functools.wraps(func) call
B. The except block should raise the exception instead of continue
C. The loop should be a while loop instead of for loop
D. The function does not return the result or stop retrying on success

Solution

  1. Step 1: Check retry logic

    The wrapper calls func() but never returns its result or breaks loop on success.
  2. Step 2: Effect of missing return

    Without return, wrapper always completes loop and returns None, so retry never stops on success.
  3. Final Answer:

    The function does not return the result or stop retrying on success -> Option D
  4. Quick Check:

    Missing return causes always 3 retries even on success [OK]
Hint: Always return on success to stop retries [OK]
Common Mistakes:
  • Not returning function result inside try
  • Misusing continue in except block
  • Ignoring decorator metadata preservation
5. You want to implement a retry mechanism in Selenium tests that retries up to 3 times with a 2-second delay between tries. Which code snippet correctly implements this?
hard
A. import time def retry(func): def wrapper(): for i in range(3): try: return func() except Exception: if i < 2: time.sleep(2) else: raise return wrapper
B. import time def retry(func): def wrapper(): for _ in range(3): try: func() except Exception: time.sleep(2) return wrapper
C. def retry(func): def wrapper(): try: return func() except Exception: time.sleep(2) return func() return wrapper
D. import time def retry(func): def wrapper(): while True: try: return func() except Exception: time.sleep(2) return wrapper

Solution

  1. Step 1: Check retry count and delay

    import time def retry(func): def wrapper(): for i in range(3): try: return func() except Exception: if i < 2: time.sleep(2) else: raise return wrapper retries 3 times with a 2-second sleep between tries except after last attempt.
  2. Step 2: Verify exception handling

    import time def retry(func): def wrapper(): for i in range(3): try: return func() except Exception: if i < 2: time.sleep(2) else: raise return wrapper raises exception after last retry, correctly stopping retries on failure.
  3. Final Answer:

    import time def retry(func): def wrapper(): for i in range(3): try: return func() except Exception: if i < 2: time.sleep(2) else: raise return wrapper -> Option A
  4. Quick Check:

    Retry with delay and raise after last try [OK]
Hint: Use loop with sleep and raise after last retry [OK]
Common Mistakes:
  • Not raising exception after last retry
  • Missing delay between retries
  • Retrying infinitely without limit
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard