Pytest automation testing framework index.

Test More In Less Time

Run Automation Testing In Parallel On The LambdaTest Cloud

Start for free

Description

The pytest an open-source framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries.

Support and updates

  • Pytest has 8969 stars, 2078 forks.
  • It has 5 major releases in the past 6 months.
  • It has 20 commits and there are 43 open pull requests.
  • It has 764 open issues and 4237 have been closed.

Code statistics

  • Pytest has 167 methods.

Blogs

Check out the latest blogs from LambdaTest on this topic:

Python Testing Tutorial: Why Python for Test Automation

This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Python Tutorial.

Common Challenges In Selenium Automation & How To Fix Them?

Selenium is one of the most popular test frameworks which is used to automate user actions on the product under test. ​Selenium is open source and the core component of the selenium framework is Selenium WebDriver. Selenium WebDriver allows you to execute test across different browsers like Chrome, Firefox, Internet Explorer, Microsoft Edge, etc. The primary advantage of using the Selenium WebDriver is that it supports different programming languages like .Net, Java, C#, PHP, Python, etc. You can refer to articles on selenium WebDriver architecture to know more about it.

PyTest Tutorial – Python Selenium Test in Parallel

This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Python Tutorial and Selenium pytest Tutorial.

What is Selenium Grid & Advantages of Selenium Grid

Manual cross browser testing is neither efficient nor scalable as it will take ages to test on all permutations & combinations of browsers, operating systems, and their versions. Like every developer, I have also gone through that ‘I can do it all phase’. But if you are stuck validating your code changes over hundreds of browsers and OS combinations then your release window is going to look even shorter than it already is. This is why automated browser testing can be pivotal for modern-day release cycles as it speeds up the entire process of cross browser compatibility.

Selenium Automation Testing on Internet Explorer (IE) & Edge

Design and Usability are two important factors when you are building a consumer web product/web application. You might need to step into the shoes of the customers in order to tackle different usability problems. However, you may have to fill in a lot of shoes considering the fact that not all your customers would be using the same browsers as you. Cross browser testing becomes a pivotal part of every test cycle. As a tester or developer, you might be using the macOS for product development but you need to take care of scenarios where customers use deprecated browsers like Internet Explorer.

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

License

Pytest is lincensed under the MIT License

LambdaTest Community Discussions

Questions
Discussion

Pytest Setup and Teardown for Selenium Testing

Assert Exception and Print Traceback in Pytest

How to correctly use pytest mocker to patch a function?

How to send a POST request with data in Node.js?

Skip or Disable Tests in Pytest

What is the correct way to set up and tear down resources for a pytest class when using Selenium for end-to-end testing?

I need to initialize the browser in the setup_class method, perform several tests defined as class methods, and then quit the browser in the teardown_class method. However, I’m struggling to understand how to properly use setup_class and teardown_class methods in this context.

It seems like a bad solution logically, because my tests will work with the instance, not the class. Since I pass the self parameter inside every test method, I can access instance variables, but I can’t access cls variables in the same way.

Here’s the structure of my current code:

class TestClass:
  
    def setup_class(cls):
        pass
        
    def test_buttons(self, data):
        # self.$attribute can be used, but not cls.$attribute?  
        pass
        
    def test_buttons2(self, data):
        # self.$attribute can be used, but not cls.$attribute?
        pass
        
    def teardown_class(cls):
        pass

This approach doesn’t feel right for creating the browser instance at the class level. Shouldn’t the browser instance be created for each object separately instead of for the whole class?

Would it be better to use __init__ and __del__ methods instead of setup_class and teardown_class for managing browser initialization and cleanup in pytest setup?

https://community.lambdatest.com/t/35259

Instead of using setup_class and teardown_class, you can use setup_method and teardown_method to manage resources on an instance level. This means each test runs in complete isolation with its own browser instance, ensuring test independence and avoiding shared state issues.

import pytest
from selenium import webdriver

class TestClass:

    def setup_method(self):
        # Setup browser instance for each test
        self.browser = webdriver.Chrome()
    
    def test_buttons(self):
        # Use self.browser here to interact with the browser
        self.browser.get('http://example.com')
        assert self.browser.title == 'Example Domain'
    
    def test_buttons2(self):
        # Another test using its own browser instance
        self.browser.get('http://anotherexample.com')
        assert self.browser.title == 'Another Example'
    
    def teardown_method(self):
        # Teardown browser instance after each test
        if hasattr(self, 'browser'):
            self.browser.quit()

:white_check_mark: Why this works?

  • Each test runs in isolation, preventing state leakage.
  • If one test fails or crashes, it doesn’t affect others.
  • Ideal for independent, repeatable, and parallelized tests.
https://community.lambdatest.com/t/35259

If opening a new browser for every test is too slow, you might want to set up the browser once per test class. This reduces overhead but comes with a risk: tests could interfere with each other.

import pytest
from selenium import webdriver

class TestClass:

    @classmethod
    def setup_class(cls):
        # Setup browser instance once for the entire class
        cls.browser = webdriver.Chrome()
    
    def test_buttons(self):
        # Use cls.browser here, shared across tests
        self.browser.get('http://example.com')
        assert self.browser.title == 'Example Domain'
    
    def test_buttons2(self):
        # Another test using the same browser instance
        self.browser.get('http://anotherexample.com')
        assert self.browser.title == 'Another Example'
    
    @classmethod
    def teardown_class(cls):
        # Teardown browser instance once after all tests
        if hasattr(cls, 'browser'):
            cls.browser.quit()

:white_check_mark: Why this works?

  • Faster since you don’t have to create and close a browser for every test.
  • Useful when tests depend on a shared session (e.g., logging in once and running multiple tests).

:warning: Potential Issue:

  • If one test modifies the browser state (e.g., navigating to a different page), it may affect the next test.
  • Harder to parallelize tests.
https://community.lambdatest.com/t/35259

Instead of relying on pytest’s built-in setup methods, you can manage resources within the test class using __init__ and __del__.

import pytest
from selenium import webdriver

class TestClass:

    def __init__(self):
        # Initialize browser for each test instance
        self.browser = webdriver.Chrome()

    def test_buttons(self):
        # Use self.browser here to interact with the browser
        self.browser.get('http://example.com')
        assert self.browser.title == 'Example Domain'

    def test_buttons2(self):
        # Another test using the same browser instance
        self.browser.get('http://anotherexample.com')
        assert self.browser.title == 'Another Example'

    def __del__(self):
        # Cleanup browser instance when the test object is deleted
        if hasattr(self, 'browser'):
            self.browser.quit()

:white_check_mark: Why this works?

  • A clean, object-oriented approach to managing resources.
  • The browser instance exists as long as the test object is alive.
  • Automatic cleanup when the object is deleted.

:warning: Potential Issue:

  • __del__ is not always called immediately (Python’s garbage collection is unpredictable).
  • Less explicit than pytest’s built-in setup/teardown methods.
https://community.lambdatest.com/t/35259

StackOverFlow community discussions

Questions
Discussion

How do I count n-gram occurrences in many lists

How to modify failure report for specific tests

pytest fails with "ERROR: file or directory not found: and"

Output ASCII art to console on succesfull pytest run

Is there a difference between "==" and "is"?

Does Python have a ternary conditional operator?

How to pass multiple arguments in pytest using command line?

What are metaclasses in Python?

In python, how to capture the stdout from a c++ shared library to a variable

How to print progress bar with negative values in Python 2.X?

Use list comprehension to generate the ngrams and collections.Counter to count duplicates:

from collections import Counter
l = ['hello', 'how', 'are', 'you', 'doing', 'today', 'are', 'you', 'okay']
ngrams = [(l[i],l[i+1]) for i in range(len(l)-1)]
print Counter(ngrams)
https://stackoverflow.com/questions/43234713/how-do-i-count-n-gram-occurrences-in-many-lists

Test case code snippets

Accessibility testing - Screen reader notifications for status messages

Description:

When conveying a status message, use ARIA live regions or ARIA alerts to announce the message to screen reader users.

Accessibility testing - Avoid time limits for tasks

Description:

Do not require time limits to complete tasks unless absolutely necessary. If a time limit is necessary, the time limit should be at least 20 hours, or it can be extended, adjusted, or disabled.

API Testing - Check auth types

Description:

Verify that the API correctly handles various types of authentication, such as basic authentication, token authentication, and OAuth.

Accessibility testing - Do not identify content based on sensory characteristics

Description:

Do not identify content based on its color, size, shape, position, sound, or other sensory characteristics.

Downloads

Pytest can be downloaded from it’s GitHub repository - https://github.com/pytest-dev/pytest

Method index

...

Automation Testing Cloud

Run Selenium, Cypress & Appium Tests Online on
3000+ Browsers.

Know More
Kane AI

Kane AI

World’s first end to end software testing agent.

Other similar frameworks

refurb

Library for refurbishing and organising Python codebases

Nose2

Nose2 is the successor to nose. Nose2's purpose is to extend unittest to make testing nicer and easier to understand. Can be considered as unittest with plugins.

freezegun

FreezeGun is a library that allows your Python tests to travel through time by mocking the datetime module.

Mamba

mamba is the definitive test runner for Python. Born under the banner of behavior-driven development. Install mamba like any other Python package using pip.

toolium

Wrapper tool of Selenium and Appium libraries to test web and mobile applications in a single project

Frameworks to try

Venom

Run and manage integration tests efficiently using Venom executors and assertions

Xunit

xUnit.net is a free, open source, community-focused unit testing tool for the .NET Framework. It is the latest technology for unit testing .NET languages.

Spork_ruby

A DRb server for testing frameworks (RSpec / Cucumber currently) that forks before each run to ensure a clean testing state.

Inspec_ruby

Tool to perform auditing and testing for inspecting infrastructure

Hikaku

Hikaku library tests if a REST-API implementation meets its specification without having to create requests which are fired against a mock server.

Run Pytest scripts on 3000+ browsers online

Perform automation testing with Pytest on LambdaTest, the most powerful, fastest, and secure cloud-based platform to accelerate test execution speed.

Test Now