Bird
Raised Fist0
Testing Fundamentalstesting~15 mins

Identifying performance bottlenecks in Testing Fundamentals - Build an Automation Script

Choose your learning style10 modes available
Identify performance bottlenecks in a web application
Preconditions (2)
Step 1: Open the web application homepage in a browser
Step 2: Start the performance recording tool in the browser DevTools
Step 3: Perform typical user actions such as loading the homepage, navigating to a product page, and adding a product to the cart
Step 4: Stop the performance recording after these actions
Step 5: Analyze the recorded timeline for long tasks, slow network requests, and rendering delays
Step 6: Identify the slowest operations or resources causing delays
✅ Expected Result: The performance report clearly shows which parts of the application cause delays, such as slow API responses, heavy scripts, or rendering bottlenecks
Automation Requirements - Selenium with Python
Assertions Needed:
Verify page load time is under acceptable threshold (e.g., 3 seconds)
Verify no network request takes longer than a set limit (e.g., 2 seconds)
Verify no JavaScript errors occur during user actions
Best Practices:
Use explicit waits to handle dynamic content
Use browser performance logs to capture network and timing data
Structure code with setup and teardown methods for browser management
Automated Solution
Testing Fundamentals
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import json

class PerformanceTest:
    def setup_method(self):
        options = webdriver.ChromeOptions()
        options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
        self.driver = webdriver.Chrome(options=options)
        self.wait = WebDriverWait(self.driver, 10)

    def teardown_method(self):
        self.driver.quit()

    def get_performance_logs(self):
        logs = self.driver.get_log('performance')
        return [json.loads(entry['message'])['message'] for entry in logs]

    def test_performance_bottlenecks(self):
        start_time = time.time()
        self.driver.get('https://example.com')
        self.wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
        load_time = time.time() - start_time

        assert load_time < 3, f"Page load took too long: {load_time:.2f} seconds"

        # Simulate user navigation
        product_link = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a.product-link')))
        product_link.click()
        self.wait.until(EC.presence_of_element_located((By.ID, 'add-to-cart')))

        add_to_cart_btn = self.driver.find_element(By.ID, 'add-to-cart')
        add_to_cart_btn.click()

        # Check for JS errors
        logs = self.driver.get_log('browser')
        js_errors = [log for log in logs if log['level'] == 'SEVERE']
        assert not js_errors, f"JavaScript errors found: {js_errors}"

        # Analyze performance logs for slow network requests
        perf_logs = self.get_performance_logs()
        slow_requests = []
        for message in perf_logs:
            if message['method'] == 'Network.responseReceived':
                request_id = message['params']['requestId']
                timing = next((m for m in perf_logs if m['method'] == 'Network.loadingFinished' and m['params']['requestId'] == request_id), None)
                if timing:
                    duration = timing['params']['timestamp'] - message['params']['timestamp']
                    if duration > 2:
                        url = message['params']['response']['url']
                        slow_requests.append({'url': url, 'duration': duration})

        assert not slow_requests, f"Slow network requests found: {slow_requests}"

This test uses Selenium with ChromeDriver to open the web application and measure page load time using Python's time module.

Explicit waits ensure elements are ready before interacting, avoiding flaky tests.

JavaScript errors are checked from browser logs to catch client-side issues.

Performance logs from Chrome capture network request timings. The test filters requests taking longer than 2 seconds and fails if any are found.

Setup and teardown methods manage browser lifecycle cleanly.

Common Mistakes - 4 Pitfalls
Using implicit waits instead of explicit waits
Not checking browser logs for JavaScript errors
Hardcoding long sleep times instead of using waits
Ignoring network request timings in performance analysis
Bonus Challenge

Now add data-driven testing with 3 different user actions sequences to measure performance for each

Show Hint

Practice

(1/5)
1. What is a performance bottleneck in software testing?
easy
A. A part of the software that slows down the whole system
B. A feature that adds new functionality
C. A test case that always passes
D. A tool used to write code faster

Solution

  1. Step 1: Understand the meaning of bottleneck

    A bottleneck is something that limits or slows down a process.
  2. Step 2: Apply this to software performance

    In software, a bottleneck is the slow part that affects the whole system's speed.
  3. Final Answer:

    A part of the software that slows down the whole system -> Option A
  4. Quick Check:

    Performance bottleneck = slow part [OK]
Hint: Bottleneck means slowest part slowing everything [OK]
Common Mistakes:
  • Confusing bottleneck with new features
  • Thinking bottleneck is a test case
  • Mixing bottleneck with coding tools
2. Which of the following is the correct way to measure execution time in Python for identifying bottlenecks?
easy
A. import time; start = time.time(); # code; end = time.time(); print(end - start)
B. import datetime; print(datetime.now())
C. print('Execution time')
D. time.sleep(5)

Solution

  1. Step 1: Identify timing method for measuring code duration

    Using time.time() before and after code gives elapsed seconds.
  2. Step 2: Check options for correct timing usage

    import time; start = time.time(); # code; end = time.time(); print(end - start) correctly measures start and end time and calculates difference.
  3. Final Answer:

    import time; start = time.time(); # code; end = time.time(); print(end - start) -> Option A
  4. Quick Check:

    Use time.time() to measure duration [OK]
Hint: Use time.time() before and after code [OK]
Common Mistakes:
  • Using print statements without timing
  • Using datetime.now() without calculating difference
  • Using sleep to measure time
3. Consider this Python code snippet measuring a function's execution time:
import time
def slow_function():
    total = 0
    for i in range(1000000):
        total += i
start = time.time()
slow_function()
end = time.time()
print(round(end - start, 2))
What is the expected output type?
medium
A. The sum of numbers from 0 to 999999
B. An error because of missing return
C. A float number showing seconds taken
D. A string 'round' printed

Solution

  1. Step 1: Understand what the code measures

    The code measures time before and after running slow_function and prints the difference rounded to 2 decimals.
  2. Step 2: Analyze output type

    round(end - start, 2) returns a float number representing seconds elapsed.
  3. Final Answer:

    A float number showing seconds taken -> Option C
  4. Quick Check:

    Timing code prints float seconds [OK]
Hint: Timing code prints float seconds elapsed [OK]
Common Mistakes:
  • Thinking it prints sum instead of time
  • Expecting an error due to no return
  • Confusing round function output
4. You have this code snippet to find a bottleneck:
import time
start = time.time()
for i in range(1000000):
    pass
print(end - start)
What is the error and how to fix it?
medium
A. Range should be 1000 instead of 1000000
B. Missing import statement for time module
C. Use print(start - end) instead
D. Variable 'end' is not defined; define end = time.time() before print

Solution

  1. Step 1: Identify the error in variable usage

    The variable 'end' is used in print but never assigned, causing a NameError.
  2. Step 2: Fix by assigning end before print

    Assign end = time.time() after the loop and before print to measure elapsed time.
  3. Final Answer:

    Variable 'end' is not defined; define end = time.time() before print -> Option D
  4. Quick Check:

    Define end = time.time() before print [OK]
Hint: Always assign end time before printing elapsed [OK]
Common Mistakes:
  • Forgetting to assign end time
  • Changing range unnecessarily
  • Subtracting times in wrong order
5. You run a profiler on your web app and find that database queries take 80% of the total time. What is the best next step to improve performance?
hard
A. Add more logging to the application
B. Optimize or reduce the number of database queries
C. Increase the size of the frontend assets
D. Rewrite the UI in a different framework

Solution

  1. Step 1: Analyze profiler results

    Profiler shows database queries consume most time, indicating a bottleneck there.
  2. Step 2: Choose action targeting bottleneck

    Optimizing or reducing queries directly addresses the slowest part to improve speed.
  3. Final Answer:

    Optimize or reduce the number of database queries -> Option B
  4. Quick Check:

    Fix bottleneck by optimizing slowest part [OK]
Hint: Fix bottleneck by improving slowest part first [OK]
Common Mistakes:
  • Changing unrelated parts like UI or logging
  • Ignoring profiler data
  • Adding features instead of fixing speed
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