Saravanan666/pypi-org huggingface dataset:
Package: pytest-ast-back-to-python
A plugin for pytest devs to view how assertion rewriting recodes the ASTFeaturesPytest rewrites the AST (abstract syntax tree) of your tests, for the purpose of displaying the subexpressions involved in your assert statements. This plugin converts that rewritten AST back to Python source, and displays it.InstallationYou can install “pytest-ast-back-to-python” viapipfromPyPI:$ pip install pytest-ast-back-to-pythonUsagepy.test--show-ast-as-pythonExampleTake a trivial test like:deftest_simple():a=1b=2asserta+b==3View the rewritten AST as Python like this:$py.test--show-ast-as-pythontest_simple.py========================================testsessionstarts========================================plugins:ast-back-to-python-0.1.0,cov-2.2.1collected1itemstest_simple.py.========================================RewrittenASTasPython========================================importbuiltinsas@py_builtinsimport_pytest.assertion.rewriteas@pytest_ardeftest_simple():a=1b=2@py_assert2=a+b@py_assert4=3@py_assert3=@py_assert2==@py_assert4if@py_assert3isNone:from_pytest.warning_typesimportPytestAssertRewriteWarningfromwarningsimportwarn_explicitwarn_explicit(PytestAssertRewriteWarning('asserting the value None, please use "assert is None"'),category=None,filename='/home/tom/.virtualenvs/tmp-483cf04ecc31dda8/test_thing.py',lineno=4)ifnot@py_assert3:@py_format6=@pytest_ar._call_reprcompare(('==',),(@py_assert3,),('(%(py0)s + %(py1)s) == %(py5)s',),(@py_assert2,@py_assert4))%{'py0':@pytest_ar._saferepr(a)if'a'in@py_builtins.locals()or@pytest_ar._should_repr_global_name(a)else'a','py1':@pytest_ar._saferepr(b)if'b'in@py_builtins.locals()or@pytest_ar._should_repr_global_name(b)else'b','py5':@pytest_ar._saferepr(@py_assert4)}@py_format8=(''+'assert %(py7)s')%{'py7':@py_format6}raiseAssertionError(@pytest_ar._format_explanation(@py_format8))@py_assert2=@py_assert3=@py_assert4=NoneContributingContributions are very welcome. Tests can be run withtox, please ensure
the coverage at least stays the same before you submit a pull request.LicenseDistributed under the terms of theBSD-3license, “pytest-ast-back-to-python” is free and open source softwareThisPytestplugin was generated withCookiecutteralong with@hackebrot’sCookiecutter-pytest-plugintemplate.IssuesIf you encounter any problems, pleasefile an issuealong with a detailed description.
Package: pytest-asteroid
OverviewASTEROID: Automated, Solution for Testing Efficiently on Replicable, Operative, and Isolated Databases.This pytest plugin is made for testing with MySQL docker images and is based on the greatlovely-pytest-dockerplugin by Lovely Systems.pytest-asteroidextends the lovely-pytest-docker plugin by adding:an availability check to make sure the MySQL image is ready for connection before running the database test suite.a simple reset state functionality to handle state dependency issues between tests.How do I get set up?DependenciesMake sure your system hasDocker Engineinstalled and that the docker daemon is running before executing your tests.InstallationInstallpytest-asteroidusing pip or poetry. We prefer to usepoetryas it reduces the amount of files needed in the project and simplifies dependency management and virtual environments.Install with poetry:$poetryaddpytest-asteroid--devExamples of usageIn order to use ASTEROID make sure to have the following environmental variables set for the test DB docker image:MYSQL_DATABASEMYSQL_ROOT_PASSWORDUsing the get_docker_db_port fixture# content from conftest.py################################################################################ * Connection to test database# This fixture uses the ASTEROID fixture get_docker_db_port which, on first# session-scoped call, will envoke the docker_service startup.################################################################################ Overwrite this fixture if a custom connection type is required################################################################################ NOTE: Here we are using class fixture as we need the connection to close again# after each test class run if we want to reset state.# If attemting to reset state, while a connection is open,# we will have a deadlock.@pytest.fixture(scope="class")defget_connection(get_docker_db_port):conn=pymysql.connect(database=os.environ["MYSQL_DATABASE"],port=get_docker_db_port("mysql_db",timeout=30.0),user="root",password=os.environ["MYSQL_ROOT_PASSWORD"],cursorclass=pymysql.cursors.DictCursor,)# Start a transaction and rollback to reset state after each test class executionyieldconnconn.close()Using the get_connection and reset_or_save_db_state fixtures# content from test_state.pyclassTestSaveState:# Test cases to check reset state worksdeftest_connection_insert(self,get_connection,reset_or_save_db_state):reset_or_save_db_state("mysql_db","superheroes")conn=get_connection# setup: insert new datawithconn.cursor()ascur:cur.execute("""INSERT INTO superheroes (name, cape, height_cm, weigth_kg)VALUES('Dr. Strange', true, 188, 82)""")conn.commit()cur.execute("SELECT * FROM superheroes WHERE name = 'Dr. Strange'")rows=cur.fetchall()assertlen(rows)==1ClarificationUse the examples in the project repository foldertests/for inspiration on how to usepytest-asteroidand to see examples of test file structure.
Package: pytest-astropy
This is a meta-package that pulls in the dependencies that are used byastropyand someaffiliated packagesfor testing. It can also be used for
testing packages that are not affiliated with the Astropy project.This package also provides pytest markers for cpu and memory intensive tests
(pytest.mark.slowandpytest.mark.hugemem). Tests marked with those
markers are not run by default, can be run with the other tests with--run-slowand--run-hugemem, and can be run separately with-mslowand-mhugemem.The package also provides the short option-Rfor--remote-data.DependenciesThe following dependencies are installed by this package:Thepytesttesting framework for Python.pytest-astropy-header, apytestplugin used for custom test header.pytest-remotedata, apytestplugin used for controlling access to data
files hosted online.pytest-doctestplus, apytestplugin that provides advanced features
for testing example code in documentation.pytest-arraydiff, apytestplugin that enables the generation and
comparison of data arrays produced during unit tests.pytest-filter-subpackage, apytestplugin that adds a-Poption to
pytest to filter by sub-package.pytest-mock,  a thin-wrapper around the mock package for easier use
withpytest.pytest-cov, apytestplugin to measure test coverage.hypothesis, a Python library for property based testing.InstallationThepytest-astropyplugin can be installed usingpip:$ pip install pytest-astropyIt is also possible to install the latest development version from the source
repository:$ git clone https://github.com/astropy/pytest-astropy
$ cd pytest-astropy
$ python ./setup.py installIn either case, the plugin will automatically be registered for use withpytest.Development StatusQuestions, bug reports, and feature requests can be submitted ongithub.LicenseThis package is licensed under a 3-clause BSD style license - see theLICENSE.rstfile.
Package: pytest-ast-transformer
[![Build Status](https://travis-ci.org/okorolev/pytest-ast-transformer.svg?branch=master)](https://travis-ci.org/okorolev/pytest-ast-transformer)[![image](https://img.shields.io/pypi/v/pytest-ast-transformer.svg)](https://pypi.org/project/pytest-ast-transformer/)## AboutAST Transformer integrated with py.test.Useful for debug, refactoring, 'clean asserts' (see [examples/replace_asserts](examples/replace_asserts))Support options---------------| Options                  | Description                    || -----------              | -----------                    || `--show-code`            | show generated code            || `--disable-transforms`   | disable all ast transformers   |## Install```bashpip install pytest-ast-transformer```## Usage* Write ast transformer```python# transformer.pyimport astfrom pytest_ast_transformer.ast_transformer import PytestTransformerdef my_assert(test_result, msg=''):print(f'my assert: {test_result} {msg}')assert test_result, msgclass AssertTransformer(PytestTransformer):context = {'my_assert': my_assert}def visit_Assert(self, node: ast.Assert) -> ast.Expr:func_name = ast.Name(id='my_assert', ctx=ast.Load())call_func = ast.Call(func=func_name, args=[node.test, node.msg], keywords=[])expr = ast.Expr(value=call_func)return ast.fix_missing_locations(expr)```* Register new ast transformer```python# conftest.pyfrom pytest_ast_transformer.ast_manager import ASTManagerfrom tests.transformer import AssertTransformerdef pytest_register_ast_transformer(ast_manager: ASTManager):ast_manager.add_transformer(AssertTransformer())```
Package: pytest-async-generators
Pytest Async GeneratorsPytest fixtures for async generatorsUsageInvoke any async generator withawait subscribe_to_messages()and thenawait wait_for_messages()to retrieve the results.import asyncio
import pytest
from typing import AsyncGenerator, Callable


@pytest.mark.asyncio
async def test_counting(subscribe_to_messages: Callable) -> None:
    async def count() -> AsyncGenerator[int, None]:
        for n in range(10):
            await asyncio.sleep(0.1)
            yield n

    subscription = await subscribe_to_messages(count())
    messages = await subscription.wait_for_messages()
    assert messages == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]subscribe_to_messages()can be passed atimeoutparameter to control how long to wait for new messages.
Package: pytest-asyncio
pytest-asynciois apytestplugin. It facilitates testing of code that uses theasynciolibrary.Specifically, pytest-asyncio provides support for coroutines as test functions. This allows users toawaitcode inside their tests. For example, the following code is executed as a test item by pytest:@pytest.mark.asyncioasyncdeftest_some_asyncio_code():res=awaitlibrary.do_something()assertb"expected result"==resMore details can be found in thedocumentation.Note that test classes subclassing the standardunittestlibrary are not supported. Users
are advised to useunittest.IsolatedAsyncioTestCaseor an async framework such asasynctest.pytest-asyncio is available under theApache License 2.0.InstallationTo install pytest-asyncio, simply:$pipinstallpytest-asyncioThis is enough for pytest to pick up pytest-asyncio.ContributingContributions are very welcome. Tests can be run withtox, please ensure
the coverage at least stays the same before you submit a pull request.
Package: pytest-asyncio-network-simulator
A plugin forpytestwhich simulates the network in variousasyncioAPIs such that rather than opening and communicating over
sockets, communcation happens directly in memory.Read more in thedocumentation on
ReadTheDocs.View the change
log.Quickstartpipinstallpytest-asyncio-network-simulatorDeveloper SetupIf you would like to hack onpytest-asyncio-network-simulator,
please check out theEthereum Development Tactical
Manualfor information on how we do:TestingPull RequestsCode StyleDocumentationDevelopment Environment SetupYou can set up your dev environment with:gitclonegit@github.com:ethereum/pytest-asyncio-network-simulator.gitcdpytest-asyncio-network-simulatorvirtualenv-ppython3venv.venv/bin/activatepipinstall-e.[dev]Testing SetupDuring development, you might like to have tests run on every file save.Show flake8 errors on file change:# Test flake8when-changed-v-s-r-1asyncio_network_simulator/tests/-c"clear; flake8 asyncio_network_simulator tests && echo 'flake8 success' || echo 'error'"Run multi-process tests in one command, but without color:# in the project root:pytest--numprocesses=4--looponfail--maxfail=1# the same thing, succinctly:pytest-n4-f--maxfail=1Run in one thread, with color and desktop notifications:cdvenvptw--onfail"notify-send -t 5000 'Test failure ⚠⚠⚠⚠⚠' 'python 3 test on pytest-asyncio-network-simulator failed'"../tests../asyncio_network_simulatorRelease setupFor Debian-like systems:apt install pandocTo release a new version:makereleasebump=$$VERSION_PART_TO_BUMP$$How to bumpversionThe version format for this repo is{major}.{minor}.{patch}for
stable, and{major}.{minor}.{patch}-{stage}.{devnum}for unstable
(stagecan be alpha or beta).To issue the next version in line, specify which part to bump, likemake release bump=minorormake release bump=devnum.If you are in a beta version,make release bump=stagewill switch to
a stable.To issue an unstable version when the current version is stable, specify
the new version explicitly, likemake releasebump="--new-version4.0.0-alpha.1devnum"
Package: pytest-async-mongodb
This is a pytest plugin based onpytest-mongodbandmongomockthat enables you
to test your code that relies on a callback- or Future-based API for non-blocking access
to a MongoDB and expects certain data to be present.
It allows you to specify fixtures for database collections in JSON/BSON or YAML
format. Under the hood we use the mongomock library, that you should
consult for documentation on how to use MongoDB mock objects. If suitable you
can also use a real MongoDB server.ConfigurationIf you don’t want to put your database fixtures on the top-level directory of your package
you have to specify a directory wherepytest-async-mongodblooks for your data definitions.To do so put a line like the following under thepytestsection of yourpytest.ini-file put a[pytest]async_mongodb_fixture_dir=tests/unit/fixturesasync_mongodb_fixtures=fixture_1fixture_2pytest-async-mongodbwould then look for files ending in.yamlor.jsonin that
directory.Unlike pytest-mongodb, you cannot specify a real MongoDB connection with the pymongo client.Basic usageAfter you configuredpytest-async-mongodbso that it can find your fixtures you’re ready to
specify some data. Regardless of the markup language you choose, the data is provided
as a list of documents (dicts). The collection that these documents are being inserted
into is given by the filename of your fixture-file. E.g.: If you had a file namedplayers.yamlwith the following content:-name:Mariosurname:Götzeposition:striker-name:Manuelsurname:Neuerposition:keeperyou’d end up with a collectionplayersthat has the above player definitions
inserted. If your fixture file is in JSON/BSON format you can also use BSON specific
types like$oid,$date, etc.You get ahold of the database in your test-function by using theasync_mongodbfixture
like so:@pytest.mark.asyncioasyncdeftest_players(async_mongodb):manuel=awaitasync_mongodb.players.find_one({'name':'Manuel'})assertmanuel['surname']=='Neuer'For further information refer to themongomockdocumentation.
Package: pytest-async-sqlalchemy
pytest-async-sqlalchemyDatabase testing fixtures using the SQLAlchemy asyncio APIYou can install "pytest-async-sqlalchemy" viapipfromPyPI$ pip install pytest-async-sqlalchemySetupProviding a Session Scoped Event LoopThe first thing to do is to declare aneven_loopfixture  with the scope set as "session".
You can copy & paste the code below to yourconftest.py:@pytest.fixture(scope="session")
def event_loop():
    """
    Creates an instance of the default event loop for the test session.
    """
    if sys.platform.startswith("win") and sys.version_info[:2] >= (3, 8):
        # Avoid "RuntimeError: Event loop is closed" on Windows when tearing down tests
        # https://github.com/encode/httpx/issues/914
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    loop = asyncio.new_event_loop()
    yield loop
    loop.close()This is required sincepytest-async-sqlalchemyshares the database connection between tests
for performance reasons, but the defaulteven_loopfixture defined bypytest-asynciois function scoped1(i.e., it
kills the database connection after each test).Providing Database URL and Initializationpytest-async-sqlalchemyprovides placeholders to configure and initialize
the testing database:database_urlandinit_database. These twomustbe
defined in your projectconftest.pylike below:@pytest.fixture(scope="session")
def _database_url():
    return "postgresql+asyncpg://postgres:masterkey@localhost/dbtest"


@pytest.fixture(scope="session")
def init_database():
    from myprorject.db import metadata

    return metadata.create_allThe_database_urlmust be a session-scoped fixture that returns the database URL in
SQLAlchemy standard.init_databasemust also be a session-scoped fixture that returns
the callable used to initialize the database (in most cases, this would return themetadata.create_allfunction).UsageThis plugin provides the following fixtures:db_session: AnAsyncSessionobject bounded to the test session database. Database
transactions are discarded after each test function, so the same database is used for
the entire test suite (avoiding the overhead of initializing a database on every test).database: An URL to the initialized test session database.scoped_database:scoped_databaseprovides a new database within the scope of the
test function. The value of the fixture is a string URL pointing to the database.ContributingContributions are very welcome. Tests can be run withtox, please ensure
the coverage at least stays the same before you submit a pull request.LicenseDistributed under the terms of theMITlicense, "pytest-async-sqlalchemy" is free and open source software1.pytest-async-sqlalchemycan't provide its owneven_loopsince pytest plugins are not
able to override fixtures from one another. So the only solution we have now is to aks the user to
declare its ownevent_loopfixture. Suggestions on how to overcome that in a better way are
welcome, hit us on the Issues section.
Package: pytest-atomic
Welcome to pytest-atomicSkip rest of tests if previous test failed.Requirementspytest >= 3.10.0python >= 3.6Not compatible with Python2.xHow to install$ pip install pytest-atomic --upgradeUsage# pytest.ini[pytest][atomic]enable:trueelectronic:trueOptionsNotice![pytest]section must be included.Notice!All options bellow must be under [atomic] section in pytest.ini.enable     : [true / false] default is falseelectronic : [true / false] default is trueExampleimportpytest@pytest.mark.atomicdeftest_fn1():assert0deftest_fn2():assert0classTestCls:@pytest.mark.atomicdeftest_1(self):assert0@pytest.mark.electronicdeftest_2(self):assert1deftest_3(self):assert0@pytest.mark.electronicdeftest_4(self):assert1deftest_5(self):assert0deftest_fn3():assert0@pytest.mark.atomicdeftest_fn4():assert0deftest_fn5():assert0test_demo
|____ test_fn1: Failed
|____ test_fn2: Skipped
|____ TestCls
|   |____ test_1 Failed
|   |____ test_2 Passed
|   |____ test_3 Skipped
|   |____ test_4 Passed
|   |____ test_5 Skipped
|
|____ test_fn3: Skipped
|____ test_fn4: Failed
|____ test_fn5: SkippedContributingContributions are very welcome. Tests can be run withtox, please ensure
the coverage at least stays the same before you submit a pull request.LicenseDistributed under the terms of theMITlicense, "pytest-atomic" is free and open source softwareKnown IssueMark a Test class directly seems not work, but you can mark the first of test method in that class.
Package: pytest-attrib
pytest-attribThepytest-attribplugin extends py.test with the ability to select tests
based on a criteria rather than just the filename or pytest.marks. For
example, you might want to run only tests that need internet connectivity,
or tests that are slow.Thepytest.markplugin already
provides a featrure to mark tests and run only the marked tests. This plugin
also allows to run expressions on the attributes of the class, and does not
require the pytest.mark decorator.It offers features similar to the nose pluginnose-attrib.InstallationInstall the plugin with:pip install pytest-attribUsage examplesTo use the plugin, the-aCLI argument has been provided. Consider a
project with the test file:import unittest

class MyTestCase(unittest.TestCase):
    def test_function(self):
        assert 1 == 1

class MySlowTestCase(unittest.TestCase):
    slow = True

    def test_slow_function(self):
        import time
        time.sleep(5)
        assert 1 == 1Using pytest-attrib, only the slow tests can be run using:$ py.test -a slowOr run only the fast tests using:$ py.test -a "not slow"The expression given in the-aargument can be even more complex, for
example:$ py.test -a "slow and requires_internet"
$ py.test -a "slow and not requires_internet"It can also do conditional arguments like:$ py.test -a "speed=='slow' and requires_internet"LICENSEThis code falls under theMIT License.
Please note that some files or content may be copied from other places
and have their own licenses. Dependencies that are being used to generate
the databases also have their own licenses.
Package: pytest-autocap
Pytest AutocapPytest Autocap, if enabled, will automatically capture the output written tostdoutandstderr, writing it down into an output directory of your choosing.Each test is assigned a unique output directory in a way closely following how pytest refers to tests, e.g.tests/package_b/test_module_b.py::TestModBClass::test_two[2]is located intests/package_b/test_module_b/TestModBClass/test_two[2]inside the output directory.
Seepytest-autocap-exampleif you want to try this out in practice, or want to read a detailed example.Having all test output recorded automatically is helpful in case Pytest is driving long-running integration- or full-spectrum systems tests. Likewise, having a well-defined scheme for storing additional data generated as part of running these tests, can help splitting the test execution, which in case of systems tests may be significant, from subsequent analysis.How to useInstallationInstallpytest-autocap:pip install pytest-autocapCapture test output... define some tests and add the--autocap-dirargument to pytest when running to capture output:pytest --autocap-dir=/tmp/my-test-output -s .Note,-sis equivalent to--capture=noand is required for autocap to capture test output. However, autocap will raise an error if you provide--autocap-dir, but fail to also set-s/--capture=no.Storing additional files in the test output directoryIf a test generates additional data you wish to keep, use theautocap_dirfixture, which returns apathlib.Pathobject. For example:deftest_function_test(autocap_dir):withopen(autocap_dir/"stuff.txt","w")asfh:fh.write("hello, world\n")passHow it worksAutocap re-uses the capture fixture code which the various capture fixtures uses.To capture output with plain Pytest, one of these capture fixtures (capfd,capfdbinary,capsys,capsysbinary) must be referenced in the argument list of a test function or function-scoped fixture.
However, these fixtures do not support capturing output for fixtures with a longer life-time, i.e. fixtures withsession-,module- orclass-wide scope.To circumvent this requirement, and to track which fixture generates what output, autocap manually intializes capture fixtures using various pytest hooks and fixture finalizers.
All output is then stored until the test run is completed, at which point all fixtures have run their tear-down logic, and all output is finally written to the chosen output directory.
To see a detailed example, seepytest-autocap-example.LimitationsYou cannot mix autocap with the standard capture fixtures (capfd,capfdbinary,capsys,capsysbinary), or fixtures depending on those capture fixtures.In case you do by mistake, pytest will exit with a helpful error message, pointing out which test or fixture caused the issue.