Saravanan666/pypi-org huggingface dataset:
Package: pytest-line-profiler-apn
pytest-line-profiler-apnline-by-line profiling for code executed by pytest, usingline-profiler.Why?Line profiler is a wonderful tool to easily identify bottlenecks inside specific functions of your code, and quantify the improvements after a refactor.Using it is straightforward but required to instrument the functions you want to profile with a "virtual"@profiledecorator
and then execute "a trigger script" (code that calls the decorated functions somehow) viakernprof.pywhich works as a python wrapper that understands the decorator, register the functions to be profiled, and print the stats when the script finishes.Altought it does its job, is a bit invasive: you need to have an special "instrumented" version of your code,
and execute it in a way that potentially clashes with the way you do normally (for instance, through a shortcut command from your editor, a test runner, another script, etc.)Moreover, frequently in real case scenarios, "a trigger script" isn't just a simple function call.
You need to prepare input data, connect to external resources, etc. And that's exactly what a test can do, right?InstallationYou can install "pytest-line-profiler" viapipfromPyPI:$ pip install pytest-line-profilerUsageMark your test passing the functions you wants to profile as positional arguments,
like@pytest.mark.line_profile.with_args(function1, function2, [...])If your test exercises any of those functions, you'll get the profile result as a report.For example:importpytestdeff(i):returni*10defg(n=10):returnsum(f(i)foriinrange(10))@pytest.mark.line_profile.with_args(f,g)deftest_as_mark():assertg()==450After that test is executed, you'll get the stats from the line profiler instance.============ Line Profile result for tests/test_line_profiler.py::test_as_mark ============
Timer unit: 1e-06 s

Total time: 4e-06 s
File: /home/tin/lab/pytest-line-profiler/tests/test_line_profiler.py
Function: f at line 4

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     4                                           def f(i):
     5        10          4.0      0.4    100.0      return i * 10

Total time: 3e-05 s
File: /home/tin/lab/pytest-line-profiler/tests/test_line_profiler.py
Function: g at line 7

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     7                                           def g(n=10):
     8         1         30.0     30.0    100.0      return sum(f(i) for i in range(10))Alternatively, you can run any test passing the function/s to profile from the command line$ pytest --line-profile path.to.function_to_be profiled [...]ContributingContributions are very welcome. Tests can be run withpytest, please
ensure the coverage at least stays the same before you submit a pull
request.LicenseDistributed under the terms of theMITlicense,
"pytest-line-profiler" is free and open source softwareIssuesIf you encounter any problems, pleasefile an issuealong with a
detailed description.
Package: pytest-litf
pytest-litfA pytest plugin that stream output in JSON compatible withLanguage Independent Test Format.It can be used withBalto: BAlto is a Language independent Test Orchestrator.ThisPytestplugin was
generated withCookiecutteralong withhackebrot'sCookiecutter-pytest-plugintemplate.FeaturesTODORequirementsTODOInstallationYou can install "pytest-litf" viapipfromPyPI:$ pip install pytest-litfUsageTODOContributingContributions are very welcome.LicenseDistributed under the terms of theMITlicense, "pytest-litf" is
free and open source softwareIssuesIf you encounter any problems, pleasefile an
issuealong with
a detailed description.
Package: pytest-local-badge
Pytest local badgePytest extension to generate SVG badge files with pytest stats (number of tests passed,pytest-covcoverage statistics.)MotivationEveryone likes pretty code status badges.  However, hosting them can get bit troublesome when working on private projects.This pytest plugin sidesteps the problem by generating local badge files that you can simply add to the project repository and reference in theREADME.mddirectly.Having a bit of extra noise in your change history is worthy cost of having pretty badges, right?Installationpip install pytest-local-badgeUsageThe only thing you have to tell the plugin is where to store badges:pytest --local-badge-output-dir badges/All supported badges will be stored that directory.  You can find the complete list of supported options by callingpytest -hand looking for all configuration parameters starting with--local-badge-*.Here are the options available at the moment:--no-local-badge      Disable the local badge plugin.
--local-badge-output-dir=LOCAL_BADGE_OUTPUT_DIR
                        The directory to save local badges to.
--local-badge-generate={cov,status} [{cov,status} ...]
                        List of local badges to generate.
--local-badge-status-file-name=LOCAL_BADGE_STATUS_FILE_NAME
                        Desired output file name
--local-badge-cov-file-name=LOCAL_BADGE_COV_FILE_NAME
                        Desired output file nameSupported badges:status-- Number of tests (total & passed)cov-- Coverage report as perpytest-covplugin (thepytest-covmust be installed separately.)
Package: pytest-localftpserver
A PyTest plugin which provides an FTP fixture for your testsFree software: MIT licenseDocumentation:https://pytest-localftpserver.readthedocs.io/en/latest/index.htmlAttention!As of version1.0.0the support for python 2.7 and 3.4 was dropped.
If you need to support those versions you should pin the version to0.6.0,
i.e. add the following lines to your “requirements_dev.txt”:# pytest_localftpserver==0.6.0
https://github.com/oz123/pytest-localftpserver/archive/v0.6.0.zipUsage Quickstart:This Plugin provides the fixturesftpserverandftpserver_TLS,
which are threaded instances of a FTP server, with which you can upload files and test FTP
functionality. It can be configured using the following environment variables:Environment variableUsageFTP_USERUsername of the registered user.FTP_PASSPassword of the registered user.FTP_PORTPort for the normal ftp server to run on.FTP_HOMEHome folder (host system) of the registered user.FTP_FIXTURE_SCOPEScope/lifetime of the fixture.FTP_PORT_TLSPort for the TLS ftp server to run on.FTP_HOME_TLSHome folder (host system) of the registered user, used by the TLS ftp server.FTP_CERTFILECertificate (host system) to be used by the TLS ftp server.See thetests directoryor thedocumentationfor examples.You can either set environment variables on a system level or use tools such aspytest-envortox, to change the default settings of this plugin.
Sample config for pytest-cov:$ cat pytest.ini
[pytest]
env =
    FTP_USER=benz
    FTP_PASS=erni1
    FTP_HOME = /home/ftp_test
    FTP_PORT=31175
    FTP_FIXTURE_SCOPE=function
    # only affects ftpserver_TLS
    FTP_PORT_TLS = 31176
    FTP_HOME_TLS = /home/ftp_test_TLS
    FTP_CERTFILE = ./tests/test_keycert.pemSample config for Tox:$ cat tox.ini
[tox]
envlist = py{36,37,38,39,310}

[testenv]
setenv =
    FTP_USER=benz
    FTP_PASS=erni1
    FTP_HOME = {envtmpdir}
    FTP_PORT=31175
    FTP_FIXTURE_SCOPE=function
    # only affects ftpserver_TLS
    FTP_PORT_TLS = 31176
    FTP_HOME_TLS = /home/ftp_test_TLS
    FTP_CERTFILE = {toxinidir}/tests/test_keycert.pem
commands =
    pytest testsCreditsThis package was inspired by,https://pypi.org/project/pytest-localserver/made by Sebastian Rahlf, which lacks an FTP server.This package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.
Package: pytest-localstack
pytest-localstack is a plugin forpytestto createAWSintegration tests
via aLocalstackDocker container.Read The DocsRequires:pytest >= 3.3.0DockerTested against Python >= 3.6.FeaturesCreatepytest fixturesthat start and stop a Localstack container.Temporarily patch botocore to redirect botocore/boto3 API calls to Localstack container.Plugin system to easily extend supports to other AWS client libraries such asaiobotocore.Exampleimportboto3importpytest_localstacklocalstack=pytest_localstack.patch_fixture(services=["s3"],# Limit to the AWS services you need.scope='module',# Use the same Localstack container for all tests in this module.autouse=True,# Automatically use this fixture in tests.)deftest_s3_bucket_creation():s3=boto3.resource('s3')# Botocore/boto3 will be patched to use Localstackassertlen(list(s3.buckets.all()))==0bucket=s3.Bucket('foobar')bucket.create()assertlen(list(s3.buckets.all()))==1Servicesapigatewaycloudformationcloudwatchdynamodbdynamodbstreamsec2esfirehoseiamkinesislambdalogsredshiftroute53s3secretsmanagersessnssqsssmstepfunctionsstsInstallation$pipinstallpytest-localstackTODOMore detailed docs.Break Docker container running out of LocalstackSession.Make botocore patching more comprehensible.Add common test resource fixture factories i.e. S3 buckets, SQS queues, SNS topics, etc.Test this works for non-localhost Docker containers.Add other client libraries such asaiobotocore.
Package: pytest-lock
pytest-lockOverviewpytest-lockis a pytest plugin that allows you to "lock" the results of unit tests, storing them in a local cache.
This is particularly useful for tests that are resource-intensive or don't need to be run every time. When the tests are
run subsequently.pytest-lockwill compare the current results with the locked results and issue a warning if there
are any discrepancies.Free software: Apache licenseDocumentation:https://pytest-lock.readthedocs.io/en/latest/Source:https://github.com/Athroniaeth/pytest-lockBugs:https://github.com/Athroniaeth/pytest-lock/issuesContributing:https://github.com/Athroniaeth/pytest-lock/blob/main/CONTRIBUTING.mdInstallationTo install pytest-lock, you can use pip:pipinstallpytest-lockUsageLocking TestsTo lock a test, use the lock fixture. Here's an example:frompytest_lockimportFixtureLockdeftest_lock_sum(lock:FixtureLock):args=[1,2,3]lock.lock(sum,(args,))...Run pytest with the--lockoption to generate the lock files:pytest--lockThis will generate JSON files in a.pytest-lockdirectory, storing the results of the locked tests.Running TestsSimply run pytest as you normally would:pytestIf pytest detect the presence of lock fixtures in your tests, it will compare the results of the tests with the locked
If a test result differs from its locked value, a warning will be issued.ConfigurationThe locked test results are stored in a.pytest-lockdirectory at the root of your project. You can delete this
directory to reset all locks.ContributingContributions are welcome! Please read the contributing guidelines to get started.LicenseThis project is licensed under the MIT License - see the LICENSE.md file for details.
Package: pytest-lockable
pytest-lockablepytest plugin for lockable resources.Replacement for Jenkins lockable -plugin.
Locking is implemented using<resource-id>.pidfiles and is released automatically.Resources are automatically released when pytest ends.Resources are described in json file as array of objects. Each object has some mandatory fields but can contains any other as well. Required fields are:id,online,hostname.Exampleresources.json[
  {
    "id": "1234",
    "online": true,
    "hostname": "localhost",
    "os": "Android"
  }
]idshould be unique for each resources.onlinedescribes if resource are available for allocator. Set thisfalseif you don't want to allocate resource.hostnameis used to select suitable resource by running host.Usage:pytest --allocation_hostname localhost -s --allocation_requirements os=Android my_testinstallationRequires:python 3.7<pipinstallpytest-lockableintegrationspytest-lockable integrates pytest-metadata - when resource is
reserved andpytest-metadataplugin are in use metadata will
be generated from resource json withresource_-prefixes.
e.g.resource_id=<id>.
Same dictionary are also recorded to testsuite property usingrecord_testsuite_property-method.UsageCustom options:--allocation_hostname=<hostname>, default=<os-hostname>  Allocation host
--allocation_requirements=<requirements>                 Resource requirements to be allocate
--allocation_timeout=<timeout>, default=10               Allocation timeout in seconds
--allocation_resource_list_file=<filename>, default=resources.json 
                                                         Available resorces list
--allocation_lock_folder=<folder>, default=<os-tmp-path> allocation lockfiles folder<requirements>can be json-string or key-value pairs. requirements have to match available resources to make allocation possible. Key-value pairs example:key=value&key2=value2Example:Use shared lockable resourcedeftest_example(lockable_resource):""" Simple test """print(f'Testing with resource:{lockable_resource}')Allocate lockable resource during test with given requirementsdeftest_example(lockable):""" Simple test """withlockable.auto_lock({"my":"requirements"})asallocation:print(f'Testing with resource#:{allocation.resource_id}')Seeexample test. Usage:cd example
pytest --allocation_hostname localhost -s --allocation_lock_folder . .
Package: pytest-locker
PyTest-LockerPyTest-Locker: The fastest way to check for unexpected changes between test runsThe general conceptIn essense Pytest-Locker changes the basis of testing from having to assert everything that is relevant about an object
to only having to assert that an object should not change unexpectedly (i.e. the object is locked).This, of course, implies that the pytest-locker approach makes a lot of sense
when the assertion logic becomes complex. I found it especially handy when testing if I'm sending the right API calls.Since objects can be just about anything in python
(output, state, or even function calls viamocking)
you can use this approach for just about everything.Since you need to validate if the object to lock is correct, both in the first run and after desired modifications,
the test flow is slightly different:Why use PyTest-LockerTime efficient: No need to hard code expected responses. (Especially usefull for data heavy unittests)Easy to verify changes:Seperates the logic of the test from the expected values.The lock files (containing the expected values), and changes to them, are easy to interpret. This makes it really
simple to evaluate changes during testing, in commits and in pull request.Installrunpip install pytest-lockerUsageConfiguring the project and writing your first test.Addfrom pytest_locker import lockerto yourconftest.pyfileTo access the locker by adding it to the method parameters i.e.def test_example(locker)Uselocker.lock(your_string, optional_name)to lock the data (of-course you can also lock other types).Ensure that thepytest rootdiris fixed.
Seethe pytest customize documentationfor all the options (one
is adding apytest.inito the root folder)Ensure that.pytest_locker/is synced via git, to ensure that you, your team, and your CI/CD pipelines are working
with the same data.And you're all set!Accepting the current behavior and checking fo changes in this behaviorThere are two modes based on for locking. The first isWhen user input is allowed, i.e. when running pytest with--capture  noor-sWhen user input is allowed and the given data does not correspond to the data in the lock theuser is promptedif
the new data should be stored or if the tests should fail.When user input is captured which is default behavior for pytestIf user input is not allowed the tests willautomatically failif the expected lock file does not exist or if the
data does not correspond to the data in the lock file.The Locker classYou can also usepytest_locker.Locker(i.e. the class of which thelockerfixture returns an instance) directly to create fixtures that locks a (non-string) object without needing to
turn the object into a string it.ExamplesFor example of use look at the tests inrepr-utils.
Package: pytest-logfest
Pytest plugin providing three logger fixtures with basic or full writing to log filesFeaturesThree logger fixtures, one of each scope: session, module and function.Three options for writing log records to file: quiet, basic, full.RequirementsPytestPathlib2 (if using Python 2.7)InstallationYou can install “pytest-logfest” viapipfromPyPI:$ pip install pytest-logfestUsageFixturesThe three logger fixtures exposed by this plugin are:session_loggermodule_loggerfunction_loggerThey expose a PythonLoggerobject, so you can use them as such, e.g.session_logger.INFO("Thisis a log record of levelINFO.")The log nodes of these loggers match the path to the corresponding location or file.Pytest’s--log-cli-level=<level>will display these log records on stdout.Log filenamesWriting the log records of the loggers to file can be controlled by the--logfestcommand-line option:--logfest=quietor option omitted: no log files are written.--logfest=basic: one log file containing INFO and higher for passed tests, DEBUG and higher for setup errors or failed tests.--logfest=full: in addition to the basic log file, all log records are written to a session log file and one log file per module.Log file names and locations are as follows (directories will be created if needed):basic log file in./artifacts:session-<sessiontimestmap>.logsession-level full log file in./artifacts:<request.node.name |logfest-root-node>-<sessiontimestmap>.logmodule-level full log file in./artifacts/<path-to-module>:<module_name>-<sessiontimestmap>.loglogfest-root-nodecan be set inpytest.ini(see below). You can change the compostion of file names through hooks (see below).pytest.iniThe following values inpytest.iniare relevant to this plugin:logfest-root-node: name used as root log node and in log filenames; if not set, defaults to the session’srequest.node.name.log-level: should be set toinfoor lower, so pytest captures all relevant log records.log-format: the default format is not very convenient in combination with this plugin, suggestion:%(name)s - %(levelname)s - %(message)sHooksThere are three hooks to change the components of the log filenames:pytest_logfest_log_file_name_basicpytest_logfest_log_file_name_full_sessionpytest_logfest_log_file_name_full_moduleThe expose a list that will be joined with the separator character-and appended with.log.ContributingContributions are very welcome. Tests can be run withtox, please ensure
good test coverage before you submit a pull request.LicenseDistributed under the terms of theMITlicense, “pytest-logfest” is free and open source software.IssuesIf you encounter any problems, pleasefile an issuealong with a detailed description.AcknowledgementsThispytestplugin was generated withCookiecutteralong with@hackebrot’scookiecutter-pytest-plugintemplate.Thanks to my employerMendix, for the crafting days in which I worked on this plugin, and for the permission to open-source it.
Package: pytest-logger
Pytest-logger is a pytest plugin configuring handlers for loggers from Python logging module.You can install pytest-logger viapipfromPyPI:$ [sudo] pip install pytest-loggerPlugin puts logs on per-logger basis to:standard output,files within log-specific directory under pytest’stmpdir_factorysession directory.You can setup plugin using hook:#conftest.py
import os

def pytest_logger_config(logger_config):
    logger_config.add_loggers(['foo', 'bar', 'baz'], stdout_level='info')
    logger_config.set_log_option_default('foo,bar')

def pytest_logger_logdirlink(config):
    return os.path.join(os.path.dirname(__file__), 'mylogs')have logging tests or libraries (including fixtures):#test_something.py
import pytest
import logging

foo = logging.getLogger('foo')
bar = logging.getLogger('bar')
baz = logging.getLogger('baz')

@pytest.yield_fixture(scope='session')
def session_thing():
    foo.debug('constructing session thing')
    yield
    foo.debug('destroying session thing')

@pytest.yield_fixture
def testcase_thing():
    foo.debug('constructing testcase thing')
    yield
    foo.debug('destroying testcase thing')

def test_one(session_thing, testcase_thing):
    foo.info('one executes')
    bar.warning('this test does nothing aside from logging')
    baz.info('extra log, rarely read')

def test_two(session_thing, testcase_thing):
    foo.info('two executes')
    bar.warning('neither does this')
    baz.info('extra log, not enabled by default')and expect output in terminal (if not captured):$ py.test -s -v
(...)
test_something.py::test_one
00:00.002 inf foo: one executes
00:00.002 wrn bar: this test does nothing aside from logging
PASSED

test_something.py::test_two
00:00.000 inf foo: two executes
00:00.000 wrn bar: neither does this
PASSEDbeing able to change this output by cmdline option:$ pytest -s -v --log foo.debug,baz
(...)
test_something.py::test_one
00:00.002 dbg foo: constructing session thing
00:00.002 dbg foo: constructing testcase thing
00:00.002 inf foo: one executes
00:00.003 inf baz: extra log, rarely read
PASSED

test_something.py::test_two
00:00.000 dbg foo: constructing testcase thing
00:00.000 inf foo: two executes
00:00.001 inf baz: extra log, not enabled by default
PASSEDand - the same - in filesystem:$ file mylogs
mylogs: symbolic link to `/tmp/pytest-of-aurzenligl/pytest-48/logs'

$ tree mylogs
mylogs
`-- test_something.py
    |-- test_one
    |   |-- bar
    |   |-- baz
    |   `-- foo
    `-- test_two
        |-- bar
        |-- baz
        `-- fooDistributed under the terms of theMITlicense, pytest-logger is free and open source software.
Package: pytest-logging
Configures logging and allows tweaking the log level with a py.test flagThisPytestplugin was generated withCookiecutteralong with@hackebrot’sCookiecutter-pytest-plugintemplate.FeaturesConfigures python’s logging to output log messages to the console(You need to tellPyTestnot to capture output).Increases the logging verbosity by lowering the log level by passing-vtoPyTestRequirementsNone!InstallationYou can install “pytest-logging” viapipfromPyPI:$ pip install pytest-loggingUsageSimply pass one or more-vflag(s) toPyTestto increase logging verbosityContributingContributions 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 theApache 2.0license, “pytest-logging” is free and open source softwareIssuesIf you encounter any problems, pleasefile an issuealong with a detailed description.
Package: pytest-loop
pytest-loop is a plugin forpytestthat makes it
easy to loop a single test, or multiple tests, a specific number of times or for a certain duration of time.
This plugin merges pytest-repeat and pytest-stress with a fix for test results.RequirementsYou will need the following prerequisites in order to use pytest-loop:
- Python 3.6+ or PyPy
- pytest 6 or newerOnly tested with Pytest version 6.2.5 and 7.0.1.InstallationTo install pytest-loop:$pipinstallpytest-loopUsageIterative Loop:Use the--loopcommand line option to specify how many times you want
your test, or tests, to be run:$pytest--loop=10test_file.pyEach test collected by pytest will be runntimes.If you want to mark a test in your code to be looped a number of times, you
can use the@pytest.mark.loop(n)decorator:importpytest@pytest.mark.loop(3)deftest_loop_decorator():passTime based loop:Loop tests for 30 seconds:$ pytest --seconds 30Loop tests for 45 minutes:$ pytest --minutes 45Loop tests for 8 hours:$ pytest --hours 8Loop tests for 1 hour 8 minutes and 9 seconds:$ pytest --hours 1 --minutes 8 --seconds 9Need to wait some time after each test loop?:$ pytest --delay 5 --hours 4 --minutes 30You can also add these values to config files:[pytest]
addopts = --hours 1 --minutes 30Note: These loop times include setup and teardown operations as well. So if you have a test setup that takes 5
seconds, your actual tests will run for 5 seconds less than your desired time.looping a test until failure:If you are trying to diagnose an intermittent failure, it can be useful to run the same
test over and over again until it fails. You can use pytest’s-xoption in
conjunction with pytest-loop to force the test runner to stop at the first failure.
For example:$pytest--loop=1000-xtest_file.pyThis will attempt to run test_file.py 1000 times, but will stop as soon as a failure
occurs.$pytest--hours10-xtest_file.This will attempt to run test_file.py for 10 hours, but will stop as soon as a failure
occurs.ResourcesRelease NotesIssue TrackerCode