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:

Automate Browser Testing with Selenium Opera in Python Easily

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

22 Practical Tips To Test Automation With Selenium WebDriver

Test automation with Selenium has empowered website testers over the globe to perform automated website testing with ease. Webdriver is a core component of the Selenium framework using which you can perform automated cross browser testing of your website or web application against different types of browsers e.g. Google Chrome, Mozilla Firefox, Safari, Opera, Internet Explorer, Microsoft Edge, etc.

Easily Execute Python UnitTest Parallel Testing In Selenium

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

Cypress vs Selenium – Which Is Better ?

Selenium is one of the most prominent automation frameworks for functional testing and web app testing. Automation testers who use Selenium can run tests across different browser and platform combinations by leveraging an online Selenium Grid, you can learn more about what Is Selenium? Though Selenium is the go-to framework for test automation, Cypress – a relatively late entrant in the test automation game has been catching up at a breakneck pace.

Generating XML And HTML Report In PyUnit For Test Automation

Irrespective of the test framework being used, one aspect that would be of interest to the various stakeholders in the project e.g. developers, testers, project managers, etc. would be the output of the test results. Keeping a track of the progression of test suites/test cases and their corresponding results can be a daunting task. The task can become more complex in the later stages of the project since the product would have undergone various levels of testing.

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 send a POST request with data in Node.js?

Skip or Disable Tests in Pytest

How to correctly use pytest mocker to patch a function?

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

Dealing with multiple Python versions and PIP?

Can one get hierarchical graphs from networkx with python 3?

Manually raising (throwing) an exception in Python

How to check whether a directory is a sub directory of another directory

Get a dict of all variables currently in scope and their values

Customize pytest collecting tests

"RuntimeError: maximum recursion depth exceeded while calling a Python object" error in PyQt4 python

How can I make class properties immutable?

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

Pytest: Getting addresses of all tests

The current recommendation is to use python -m pip, where python is the version of Python you would like to use. This is the recommendation because it works across all versions of Python, and in all forms of virtualenv. For example:

# The system default python:
$ python -m pip install fish

# A virtualenv's python:
$ .env/bin/python -m pip install fish

# A specific version of python:
$ python-3.6 -m pip install fish

Previous answer, left for posterity:

Since version 0.8, Pip supports pip-{version}. You can use it the same as easy_install-{version}:

$ pip-2.5 install myfoopackage
$ pip-2.6 install otherpackage
$ pip-2.7 install mybarpackage

EDIT: pip changed its schema to use pipVERSION instead of pip-VERSION in version 1.5. You should use the following if you have pip >= 1.5:

$ pip2.6 install otherpackage
$ pip2.7 install mybarpackage

Check https://github.com/pypa/pip/pull/1053 for more details


References:

https://stackoverflow.com/questions/2812520/dealing-with-multiple-python-versions-and-pip

Test case code snippets

General webpage functionality - Test page text justification

Description:

Page text should be left-justified.

API Testing - Check locale-based representation

Description:

Verify that the API response contains the correct resource representation based on the specified locale (e.g. en-US, fr-FR).

API Testing - Check CORS preflight

Description:

Verify that the API correctly handles CORS preflight requests and returns the correct HTTP status code and error message.

General webpage functionality - Test broken links check

Description:

Check all pages for broken links.

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