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.

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

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