kandi background
Explore Kits

pytest | pytest framework makes it easy to write small tests, yet scales | Functional Testing library

 by   pytest-dev Python Version: 7.1.1 License: MIT

 by   pytest-dev Python Version: 7.1.1 License: MIT

Download this library from

kandi X-RAY | pytest Summary

pytest is a Python library typically used in Testing, Functional Testing applications. pytest has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can install using 'pip install pytest' or download it from GitHub, PyPI.
The pytest framework makes it easy to write small tests, yet scales to support complex functional testing
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • pytest has a highly active ecosystem.
  • It has 8655 star(s) with 2012 fork(s). There are 194 watchers for this library.
  • There were 2 major release(s) in the last 6 months.
  • There are 719 open issues and 4160 have been closed. On average issues are closed in 135 days. There are 39 open pull requests and 0 closed requests.
  • It has a negative sentiment in the developer community.
  • The latest version of pytest is 7.1.1
pytest Support
Best in #Functional Testing
Average in #Functional Testing
pytest Support
Best in #Functional Testing
Average in #Functional Testing

quality kandi Quality

  • pytest has 0 bugs and 0 code smells.
pytest Quality
Best in #Functional Testing
Average in #Functional Testing
pytest Quality
Best in #Functional Testing
Average in #Functional Testing

securitySecurity

  • pytest has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • pytest code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
pytest Security
Best in #Functional Testing
Average in #Functional Testing
pytest Security
Best in #Functional Testing
Average in #Functional Testing

license License

  • pytest is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
pytest License
Best in #Functional Testing
Average in #Functional Testing
pytest License
Best in #Functional Testing
Average in #Functional Testing

buildReuse

  • pytest releases are available to install and integrate.
  • Deployable package is available in PyPI.
  • Build file is available. You can build the component from source.
  • pytest saves you 50486 person hours of effort in developing the same functionality from scratch.
  • It has 62035 lines of code, 4760 functions and 251 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
pytest Reuse
Best in #Functional Testing
Average in #Functional Testing
pytest Reuse
Best in #Functional Testing
Average in #Functional Testing
Top functions reviewed by kandi - BETA

kandi has reviewed pytest and discovered the below as its top functions. This is intended to give you an instant insight into pytest implemented functionality, and help decide if they suit your requirements.

  • Prepares the release .
  • Iterates over all plugins .
  • Configures the application to be printed .
  • Issue a git commit .
  • Get all issues .
  • Configures logging .
  • Parse the changelog for the given tag name .
  • Find next version .
  • Load and validate the given expression .
  • Print issues .

pytest Key Features

The pytest framework makes it easy to write small tests, yet scales to support complex functional testing

TypeError: __init__() got an unexpected keyword argument 'as_tuple'

copy iconCopydownload iconDownload
# in requirements.txt
werkzeug==2.0.3

PIP failed to build package cytoolz

copy iconCopydownload iconDownload
python -m pip install --user cython
python -m pip install --user cytoolz
python -m pip install --user eth-brownie
-----------------------
STEP1: python -m pip install --user cython
STEP2: python -m pip install --user cytoolz
STEP3: python -m pip install --user eth-brownie
STEP4: python -m pip install --user pipx
STEP5: python -m pipx ensurepath
STEP6: RESTARTED TERMINAL
STEP7: pipx install eth-brownie

How to query additional databases using cursor in Django Pytests

copy iconCopydownload iconDownload
class PeopleFactory(factory.django.DjangoModelFactory):
    id = factory.Sequence(lambda x: x + 1)
    name = factory.Faker('first_name')

    class Meta:
        model = People
        database = 'my_db2'

How to get caller name inside pytest fixture?

copy iconCopydownload iconDownload
import pytest


@pytest.fixture()
def setup(request):
    return request.node.name


def test_foo(setup):
    assert setup == "test_foo"

Pytest asserting fixture after teardown

copy iconCopydownload iconDownload
@pytest.fixture
def thing_create():
    # Perform all the creation steps
    thing = Thing()
    ...

    yield thing


def thing_delete(thing):
    # Perform all the deletion steps
    ...
    thing.delete()  


@pytest.fixture
def thing_all(thing_create):
    yield thing_create
    thing_delete(thing_create)


def test_thing(thing_all):
    assert thing_all.exists


def test_thing_again(thing_create):
    thing_delete(thing_create)
    assert thing_create.deleted
-----------------------
@pytest.fixture
def thing():
    thing = Thing()  # Simplified, it actually takes many lines to make a thing
    yield thing
    thing.delete()  # Simplified, it also takes a few lines to delete it

def test_thing(thing):
    assert thing.exists

def test_thing_does_a_thing(thing):
    expected = "expected"
    assert thing.do_thing() == expected

def test_thing_deletes():
    # just don't use the fixture here
    thing = Thing()
    thing.delete()
    assert thing.deleted
-----------------------
@pytest.fixture
def gen_thing():

    @contextmanager
    def cm():
        thing = Thing()  # Simplified, it actually takes many lines to make a thing
        try:
            yield thing
        finally:
            thing.delete()  # Simplified, it also takes a few lines to delete it

    yield cm


def test_thing(gen_thing):
    with gen_thing() as thing:
        assert thing.exists
    assert thing.deleted


def test_thing_again(gen_thing):
    with gen_thing() as thing:
        # Do more stuff with thing

pytest: full cleanup between tests

copy iconCopydownload iconDownload
@pytest.fixture
def myfixture(request):
    request.addfinalizer(cleanup)
    prepare_stuff()
    yield 1
-----------------------
def prepare_stuff():
    logging.warning("prepare_stuff()")

def clean_stuff():
    logging.warning("clean_stuff()")

def somecode():
    logging.warning("somecode()")
    return 0
/tmp/tmp.JOfTxVUv1z via 🐍 v3.8.10 (.env) 
❯ pytest ./test_module.py -k "test_1 or test_2"
============================= test session starts ==============================
platform linux -- Python 3.8.10, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /tmp/tmp.JOfTxVUv1z
collected 2 items                                                              

test_module.py FF                                                        [100%]

=================================== FAILURES ===================================
____________________________________ test_1 ____________________________________

myfixture = 1

    def test_1(myfixture):
        a = somecode()
>       assert a==1
E       assert 0 == 1

test_module.py:25: AssertionError
------------------------------ Captured log setup ------------------------------
WARNING  root:test_module.py:5 prepare_stuff()
------------------------------ Captured log call -------------------------------
WARNING  root:test_module.py:13 somecode()
---------------------------- Captured log teardown -----------------------------
WARNING  root:test_module.py:9 clean_stuff()
____________________________________ test_2 ____________________________________

myfixture = 1

    def test_2(myfixture):
        b = somecode()
>       assert b==1
E       assert 0 == 1

test_module.py:29: AssertionError
------------------------------ Captured log setup ------------------------------
WARNING  root:test_module.py:5 prepare_stuff()
------------------------------ Captured log call -------------------------------
WARNING  root:test_module.py:13 somecode()
---------------------------- Captured log teardown -----------------------------
WARNING  root:test_module.py:9 clean_stuff()
=========================== short test summary info ============================
FAILED test_module.py::test_1 - assert 0 == 1
FAILED test_module.py::test_2 - assert 0 == 1
============================== 2 failed in 0.03s ===============================

/tmp/tmp.JOfTxVUv1z via 🐍 v3.8.10 (.env) 
-----------------------
def prepare_stuff():
    logging.warning("prepare_stuff()")

def clean_stuff():
    logging.warning("clean_stuff()")

def somecode():
    logging.warning("somecode()")
    return 0
/tmp/tmp.JOfTxVUv1z via 🐍 v3.8.10 (.env) 
❯ pytest ./test_module.py -k "test_1 or test_2"
============================= test session starts ==============================
platform linux -- Python 3.8.10, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /tmp/tmp.JOfTxVUv1z
collected 2 items                                                              

test_module.py FF                                                        [100%]

=================================== FAILURES ===================================
____________________________________ test_1 ____________________________________

myfixture = 1

    def test_1(myfixture):
        a = somecode()
>       assert a==1
E       assert 0 == 1

test_module.py:25: AssertionError
------------------------------ Captured log setup ------------------------------
WARNING  root:test_module.py:5 prepare_stuff()
------------------------------ Captured log call -------------------------------
WARNING  root:test_module.py:13 somecode()
---------------------------- Captured log teardown -----------------------------
WARNING  root:test_module.py:9 clean_stuff()
____________________________________ test_2 ____________________________________

myfixture = 1

    def test_2(myfixture):
        b = somecode()
>       assert b==1
E       assert 0 == 1

test_module.py:29: AssertionError
------------------------------ Captured log setup ------------------------------
WARNING  root:test_module.py:5 prepare_stuff()
------------------------------ Captured log call -------------------------------
WARNING  root:test_module.py:13 somecode()
---------------------------- Captured log teardown -----------------------------
WARNING  root:test_module.py:9 clean_stuff()
=========================== short test summary info ============================
FAILED test_module.py::test_1 - assert 0 == 1
FAILED test_module.py::test_2 - assert 0 == 1
============================== 2 failed in 0.03s ===============================

/tmp/tmp.JOfTxVUv1z via 🐍 v3.8.10 (.env) 
-----------------------
pytest ./test_module.py:test_1
pytest ./test_module.py:test_2
    prepare_stuff()

    a = somecode()
    assert a==1

    clean_stuff()

    prepare_stuff()

    b = somecode()
    assert b==1

    clean_stuff()
-----------------------
pytest ./test_module.py:test_1
pytest ./test_module.py:test_2
    prepare_stuff()

    a = somecode()
    assert a==1

    clean_stuff()

    prepare_stuff()

    b = somecode()
    assert b==1

    clean_stuff()

How to test async function using pytest?

copy iconCopydownload iconDownload
import asyncio
import pytest

pytest_plugins = ('pytest_asyncio',)

@pytest.mark.asyncio
async def test_simple():
    await asyncio.sleep(0.5)
collected 1 item
test_async.py::test_simple PASSED
pytest                        6.2.5
pytest-asyncio                0.16.0
# anyio not installed
-----------------------
import asyncio
import pytest

pytest_plugins = ('pytest_asyncio',)

@pytest.mark.asyncio
async def test_simple():
    await asyncio.sleep(0.5)
collected 1 item
test_async.py::test_simple PASSED
pytest                        6.2.5
pytest-asyncio                0.16.0
# anyio not installed
-----------------------
import asyncio
import pytest

pytest_plugins = ('pytest_asyncio',)

@pytest.mark.asyncio
async def test_simple():
    await asyncio.sleep(0.5)
collected 1 item
test_async.py::test_simple PASSED
pytest                        6.2.5
pytest-asyncio                0.16.0
# anyio not installed

How to use pytest to simulate full reboot

copy iconCopydownload iconDownload
import os
import time
import signal
import multiprocessing


class MyClass(multiprocessing.Process):
    def run(self):
        # Ping localhost for a limited amount of time
        os.system("ping -c 12 127.0.0.1")


process = MyClass()
process.start()

time.sleep(4)

print("terminating early")

# Send SIGKILL signal to the entire process group
group_id = os.getpgid(process.pid)
os.killpg(group_id, signal.SIGKILL)

print("done")
import os
import time
import multiprocessing

import psutil


class MyClass(multiprocessing.Process):
    def run(self):
        # Ping localhost for a limited amount of time
        os.system("ping -c 12 127.0.0.1")


def kill_process_group(pid):
    process = psutil.Process(pid)
    children = process.children(recursive=True)

    # First terminate all children
    for child in children:
        child.kill()
    psutil.wait_procs(children)

    # Then terminate the parent process
    process.kill()
    process.wait()


process = MyClass()
process.start()

time.sleep(4)

print("terminating early")

kill_process_group(process.pid)

print("done")
-----------------------
import os
import time
import signal
import multiprocessing


class MyClass(multiprocessing.Process):
    def run(self):
        # Ping localhost for a limited amount of time
        os.system("ping -c 12 127.0.0.1")


process = MyClass()
process.start()

time.sleep(4)

print("terminating early")

# Send SIGKILL signal to the entire process group
group_id = os.getpgid(process.pid)
os.killpg(group_id, signal.SIGKILL)

print("done")
import os
import time
import multiprocessing

import psutil


class MyClass(multiprocessing.Process):
    def run(self):
        # Ping localhost for a limited amount of time
        os.system("ping -c 12 127.0.0.1")


def kill_process_group(pid):
    process = psutil.Process(pid)
    children = process.children(recursive=True)

    # First terminate all children
    for child in children:
        child.kill()
    psutil.wait_procs(children)

    # Then terminate the parent process
    process.kill()
    process.wait()


process = MyClass()
process.start()

time.sleep(4)

print("terminating early")

kill_process_group(process.pid)

print("done")

How to set environment variable in pytest

copy iconCopydownload iconDownload
DATA_ENGINEERING_BUCKET = os.environ.get("BUCKET", default="default_bucket")
import os, pytest

@pytest.fixture(scope='session')
def kinesis():
    old_environ = os.environ
    os.environ = {'BUCKET': 'test-bucket'}
    import kinesis
    os.environ = old_environ
    yield kinesis
# Do NOT import kinesis in any test file. Rely on the fixture.
class TestHandler(unittest.TestCase):
    @mock_s3
    @mock_lambda
    def test_handler(kinesis):
        actual = kinesis.handler(kinesis_stream_event, "")
        expected = {"statusCode": 200, "body": "OK"}
        assert actual == expected

-----------------------
DATA_ENGINEERING_BUCKET = os.environ.get("BUCKET", default="default_bucket")
import os, pytest

@pytest.fixture(scope='session')
def kinesis():
    old_environ = os.environ
    os.environ = {'BUCKET': 'test-bucket'}
    import kinesis
    os.environ = old_environ
    yield kinesis
# Do NOT import kinesis in any test file. Rely on the fixture.
class TestHandler(unittest.TestCase):
    @mock_s3
    @mock_lambda
    def test_handler(kinesis):
        actual = kinesis.handler(kinesis_stream_event, "")
        expected = {"statusCode": 200, "body": "OK"}
        assert actual == expected

-----------------------
DATA_ENGINEERING_BUCKET = os.environ.get("BUCKET", default="default_bucket")
import os, pytest

@pytest.fixture(scope='session')
def kinesis():
    old_environ = os.environ
    os.environ = {'BUCKET': 'test-bucket'}
    import kinesis
    os.environ = old_environ
    yield kinesis
# Do NOT import kinesis in any test file. Rely on the fixture.
class TestHandler(unittest.TestCase):
    @mock_s3
    @mock_lambda
    def test_handler(kinesis):
        actual = kinesis.handler(kinesis_stream_event, "")
        expected = {"statusCode": 200, "body": "OK"}
        assert actual == expected

How to disable server exceptions on fast-api when testing with httpx AsyncClient?

copy iconCopydownload iconDownload
# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",
# on port 123.
transport = httpx.ASGITransport(app=app, raise_app_exceptions=False,
 client=("1.2.3.4", 123))
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
    ...

Community Discussions

Trending Discussions on pytest
  • TypeError: __init__() got an unexpected keyword argument 'as_tuple'
  • PIP failed to build package cytoolz
  • How to query additional databases using cursor in Django Pytests
  • How to get caller name inside pytest fixture?
  • Pytest asserting fixture after teardown
  • pytest: full cleanup between tests
  • jaydebeapi under pytest leaking environment variable content in logs
  • How to test async function using pytest?
  • How to use pytest to simulate full reboot
  • How to set environment variable in pytest
Trending Discussions on pytest

QUESTION

TypeError: __init__() got an unexpected keyword argument 'as_tuple'

Asked 2022-Mar-29 at 23:24

While I am testing my API I recently started to get the error below.

        if request is None:
>           builder = EnvironBuilder(*args, **kwargs)
E           TypeError: __init__() got an unexpected keyword argument 'as_tuple'

/usr/local/lib/python3.7/site-packages/werkzeug/test.py:1081: TypeError

As I read from the documentation in the newer version of Werkzeug the as_tuple parameter is removed.

Part of my test code is


from flask.testing import FlaskClient

@pytest.fixture(name='test_client')
def _test_client() -> FlaskClient:
    app = create_app()
    return app.test_client()


class TestPeerscoutAPI:
    def test_should_have_access_for_status_page(self, test_client: FlaskClient):
        response = test_client.get('/api/status')
        assert _get_ok_json(response) == {"status": "OK"}

Any help would be greatly appreciated.

ANSWER

Answered 2022-Mar-29 at 13:29

As of version 2.1.0, werkzeug has removed the as_tuple argument to Client. Since Flask wraps werkzeug and you're using a version that still passes this argument, it will fail. See the exact change on the GitHub PR here.

You can take one of two paths to solve this:

  1. Upgrade flask

  2. Pin your werkzeug version

# in requirements.txt
werkzeug==2.0.3

Source https://stackoverflow.com/questions/71661851

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install pytest

You can install using 'pip install pytest' or download it from GitHub, PyPI.
You can use pytest like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Compare Functional Testing Libraries with Highest Support
Compare Functional Testing Libraries with Permissive License
Compare Functional Testing Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.