Saravanan666/pypi-org huggingface dataset:
Package: unittest-dataprovider
Disclaimer:This is a only a clone of unittest-data-provider (https://pypi.org/project/unittest-data-provider/) with the last version of https://github.com/yourlabs/unittest-data-provider (package maintener didn’t update project on Pypi and I haven’t had any answer from him to my request).Package for this snippet:http://melp.nl/2011/02/phpunit-style-dataprovider-in-python-unit-test/Install:pip install unittest-dataproviderImport:import unittest
from unittest_dataprovider import data_providerYou can then use data_provider without having to stick this snippet somewhere
…Thanks drm !Original blog post by drm pasted here in case the original link goes downPHPUnit has a handy feature with which you can provide testdata to your tests.
This is called a data provider, and is implemented by annotating a test with
@dataProvider methodName. Python’s unittest module doesn’t seem to have such a
feature.PHPUnit’s versionThe data provider returns a two-dimensional array of test arguments. For
example:class CssParserTest extends PHPUnit_Framework_TestCase {
    function setUp() {
        $this->parser = new CssParser();
    }

    /**
    * @dataProvider cssColors
    */
    function testParseColor($color, $notation) {
        $this->assertEquals($color, $this->parser->parseColor($notation));
    }


    function cssColors() {
        return array(
            array(array(0, 0, 0), '#000'),
            array(array(0, 0, 0), '#000000'),
            array(array(0, 0, 0), 'rgb(0, 0, 0)')
            array(array(0, 0, 0), 'black')
        );
    }
}Running this test would call the testParseColor() test 4 times, with each of
the arrays returned by cssColors() as the arguments.Python: providing test data using a decoratorWhile writing tests for some Python code, I discovered that Python’s unittest
doesn’t seem to have such a feature. So I implemented my own, using a
decorator:def data_provider(fn_data_provider):
    """Data provider decorator, allows another callable to provide the data for the test"""
    def test_decorator(fn):
        def repl(self, *args):
            for i in fn_data_provider():
                try:
                    fn(self, *i)
                except AssertionError:
                    print "Assertion error caught with data set ", i
                    raise
        return repl
    return test_decoratorExample usage:class CssParserTest:
    def setUp(self):
        self.parser = CssColor()

    @staticmethod
    def colors():
        return (
        ( (0, 0, 0), '#000' ),
        ( (0, 0, 0), '#000000' ),
        ( (0, 0, 0), 'rgb(0, 0, 0)' ),
        ( (0, 0, 0), 'black' )
    )

    @data_provider(colors):
    def test_parse_color(self, color, notation):
        self.assertEquals(color, self.parser.parse_color(notation))Suggestions of alternatives are greatly appreciated, by the way.
Package: unittest-data-provider
Package for this snippet:http://melp.nl/2011/02/phpunit-style-dataprovider-in-python-unit-test/Install:pip install unittest-data-providerImport:import unittest
from unittest_data_provider import data_providerYou can then use data_provider without having to stick this snippet somewhere
…Thanks drm !Original blog post by drm pasted here in case the original link goes downPHPUnit has a handy feature with which you can provide testdata to your tests.
This is called a data provider, and is implemented by annotating a test with
@dataProvider methodName. Python’s unittest module doesn’t seem to have such a
feature.PHPUnit’s versionThe data provider returns a two-dimensional array of test arguments. For
example:class CssParserTest extends PHPUnit_Framework_TestCase {
    function setUp() {
        $this->parser = new CssParser();
    }

    /**
    * @dataProvider cssColors
    */
    function testParseColor($color, $notation) {
        $this->assertEquals($color, $this->parser->parseColor($notation));
    }


    function cssColors() {
        return array(
            array(array(0, 0, 0), '#000'),
            array(array(0, 0, 0), '#000000'),
            array(array(0, 0, 0), 'rgb(0, 0, 0)')
            array(array(0, 0, 0), 'black')
        );
    }
}Running this test would call the testParseColor() test 4 times, with each of
the arrays returned by cssColors() as the arguments.Python: providing test data using a decoratorWhile writing tests for some Python code, I discovered that Python’s unittest
doesn’t seem to have such a feature. So I implemented my own, using a
decorator:def data_provider(fn_data_provider):
    """Data provider decorator, allows another callable to provide the data for the test"""
    def test_decorator(fn):
        def repl(self, *args):
            for i in fn_data_provider():
                try:
                    fn(self, *i)
                except AssertionError:
                    print "Assertion error caught with data set ", i
                    raise
        return repl
    return test_decoratorExample usage:class CssParserTest:
    def setUp(self):
        self.parser = CssColor()

    colors = lambda: (
        ( (0, 0, 0), '#000' ),
        ( (0, 0, 0), '#000000' ),
        ( (0, 0, 0), 'rgb(0, 0, 0)' ),
        ( (0, 0, 0), 'black' )
    )

    @data_provider(colors):
    def test_parse_color(self, color, notation):
        self.assertEquals(color, self.parser.parse_color(notation))Suggestions of alternatives are greatly appreciated, by the way.
Package: unittest-expander
unittest_expanderis a Python library that provides flexible and
easy-to-use tools to parametrize your unit tests, especially (but
not limited to) those based onunittest.TestCase.The library is compatible with Python 3.11, 3.10, 3.9, 3.8, 3.7, 3.6 and
2.7, and does not depend on any external packages (i.e., uses only the
Python standard library).Authors:Jan Kaliszewski (zuo)andothers…License:MIT LicenseHome Page:https://github.com/zuo/unittest_expanderDocumentation:https://unittest-expander.readthedocs.io/en/stable/InstallingThe easiest way to install the library is to execute (preferably in avirtualenv) the command:python -m pip install unittest_expander(note that you need network access to do it this way).  If you do not
have thepiptool installed – see:https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/Alternatively, you candownloadthe library source archive, unpack
it,cdto the unpacked directory and execute (preferably in avirtualenv) the following command:python -m pip install .Note: you may need to have administrator privileges if you donotoperate in avirtualenv.It is also possible to use the library without installing it: as its
code is contained in a single file (unittest_expander.py), you can
just copy it into your project.Usage exampleConsider the followinguglytest:importunittestclassTest(unittest.TestCase):deftest_sum(self):foriterable,expectedin[([],0),([0],0),([3],3),([1,3,1],5),(frozenset({1,3}),4),({1:'a',3:'b'},4),]:self.assertEqual(sum(iterable),expected)Is it cool?Not at all!So let’s improve it:importunittestfromunittest_expanderimportexpand,foreach@expandclassTest(unittest.TestCase):@foreach(([],0),([0],0),([3],3),([1,3,1],5),(frozenset({1,3}),4),({1:'a',3:'b'},4),)deftest_sum(self,iterable,expected):self.assertEqual(sum(iterable),expected)Now you have6 distinct tests(properlyisolatedand being
alwaysreported as separate tests), although they share the same
test method source.You may want to do the same in a bit more verbose and descriptive
way:importunittestfromunittest_expanderimportexpand,foreach,param@expandclassTest(unittest.TestCase):test_sum_params=[param([],expected=0).label('empty gives 0'),param([0],expected=0),param([3],expected=3),param([1,3,1],expected=5),param(frozenset({1,3}),expected=4),param({1:'a',3:'b'},expected=4).label('even dict is ok'),]@foreach(test_sum_params)deftest_sum(self,iterable,expected):self.assertEqual(sum(iterable),expected)This is only a fraction of the possibilitiesunittest_expanderoffers to you.You canlearn morefrom the actualdocumentation of the module.
Package: unittesthtmlreport
unittestreport介绍1、什么是unittestreportunittestreport是基于unittest开发的的一个功能扩展库，关于unittestreport最初在开发的时候，最初只是计划开发一个unittest生成html测试报告的模块，所以起名叫做unittestreport。在开发的过程中结合使用者的反馈，慢慢的扩展了更多的功能进去。后续还会持续的扩展和开发一些新的功能，目前实现了以下功能：HTML测试报告生成unittest数据驱动测试用例失败重运行多线程并发执行用例发送测试结果及报告到邮箱测试结果推送到钉钉测试结构推送到企业微信2、安装unittestreportunittestreport是基于python3.6开发的，安装前请确认你的python版本>3.6安装命令pip install unittestreport说明：原报告模板中的CDN站点失效了，已在1.4.2版中进行了更换，如果生成的报告样式和图表丢失，请升级unittestreport版本pip install unittestreport==1.4.23、使用文档使用文档地址：https://unittestreport.readthedocs.io/en/latest/使用问题及维护：开发者：木森WeChat:musen9111大家在使用过程中发现bug,以及使用过程中有什么问题，可以联系我
Package: unit-testing
5G00EV17-3001 Unit testingAn example project for showcasing unit testing.CategoryBadgesPyPITestsActivityQAOtherDescriptionThis project showcases how unit testing works by implementing a very simple
Python library, and adding unit tests to it. The project uses Pytest.Getting StartedDependenciesThe main project has no library dependencies, but the actual unit testing
part relies on several packages listed inpyproject.toml. But in general, you'll need:Python 3.11 or newerPoetryThe project is automatically tested on the latest versions of Windows,
Mac OS, and Ubuntu, and it has also been tested on both CPython
and PyPy. Using other implementations or operating systems
may work, but is not guaranteed.InstallationPlease see the documentationhere.Running unit testsPlease see the documentationhere.Version historyThe project's changelog can be foundhere.LicenseThis project is licensed under the MIT license - see theLICENSE-file for details.AcknowledgementsInspiration, code snippets, debugging help, etc.My fellow team members
Package: unittest_jshint
Introduction============This package integrates `JSHint`_ with Python's `unittest`_ module. Thispackage was inspired by `gocept.jslint`_.`JSHint`_ is a community-driven tool to detect errors and potential problems inJavaScript code and to enforce your team's coding conventions.It provides a special JSHintTestCase class that collects JavaScript files (ina configurable manner) and dynamically generates a test method for each filethat calls jslint on that file... contents::Usage=====To use it, create a test class like this::class MyPackageJSLintTest(unittest_jshint.JSHintTestCase):include = ('my.package.browser:js','my.package.browser:js/lib',)options = ( 'curly', 'eqeqeq', )``include`` is a list of "resource paths" of the form ``packagename:path``(passed to pkg_resources).``exclude`` can be a list of filenames (without path) that will not becollected.``options`` is a list of arguments that are passed to JSHint (see its`documentation`_ for details). The default value is::options = ()All files ending in ``.js`` contained in each of these paths will be collected,and the test class will grow a method named ``test_<filename>.js``.You can ignore JSHint error by setting ``ignore`` on the test class (a list ofsubstrings that are matched against each JHLint output line)::ignore = ("Use a named parameter",)Requirements============``unittest_jshint`` was tested with:- Python 2.6 (unittest2 required)- Python 2.7Currently I only test with `Python`_ versions that are used by `Plone`_ so itjust might work for other `Python`_ versions.``unittest_jshint`` requires ``jshint`` to be in the ``PATH`` or providingcustomized environmental variable ``UNITTEST_JSHINT_COMMAND``.Contributors============- `Rok Garbas`_, garbas.. _`JSHint`: http://www.jshint.com.. _`gocept.jslint`: http://pypi.python.org/pypi/gocept.jslint.. _`documentation`: http://www.jshint.com/options/.. _`Python`: http://www.python.org.. _`Plone`: http://www.plone.org.. _`Rok Garbas`: 'http://garbas.si
Package: unittest-mocker
unittest-mockerInspired by thepytest-mock, but written from scratch for using with
unittest and convenient tool -Class mockerInstallationpipinstallunittest-mockerUsageGeneral mocker@activate_mockerdeftest_create_client(self,mocker:Mocker):post_mock=mocker.patch('requests.post')post_mock.return_value.status_code=200post_mock.return_value.json.return_value={'msg':done}send_clients_to_crm()post_mock.assert_called_once_with(...)or you can put the mocking logic in a separate method:defmock_post(mocker,status):response=requests.Response()response.status_code=statusresponse.headers={'Location':'...'}response._content='some content'returnmocker.patch('requests.post',return_value=response)@activate_mockerdeftest_upload_post_success(mocker):mocked_post=mock_post(mocker,201)...@activate_mockerdeftest_upload_post_error(mocker):mocked_post=mock_post(mocker,500)...Detailsmocker.patchunder the hood callsunittest.mock.patchSo you can apply any arguments ofthe standard mock libraryThe same withmocker.patch.object. It has the same parameters asunittest.mock.patch.objectClass mockerBasic usage:fromunittest_mockerimportactivate_mocker,MockerfromapiimportApiClient@activate_mockerdeftest_api_client(self,mocker:Mocker):client_mock=mocker.patch_class('api.ApiClient')ApiClient(url='example.com')(command='start')client_mock.test_initialized_with(url='example.com')client_mock.mocks['__call__'].assert_called_once_with(command='start')Syntax# Variant 1mocker.patch_class(target:str,methods=Optional[list[str]])# Example:mock=mocker.patch_class('some_module.SomeClass',methods=['method_1','method_2'])# Variant 2mocker.patch_class.object(target:Union[module,class],attribute:str,methods=Optional[list[str]])# Example:importsome_modulemock=mocker.patch_class(some_module,'SomeClass',methods=['method_1','method_2'])All mocked methods are stored inmock.mocksdictionary and can be accessed:mock['__init__'].assert_called_once_with(...)patch_classalways patches class's__init__method.Also,methodsparameter also defaults to [__call__]. So that's correct:mock=mocker.patch_class('some_module.SomeClass')...mock.mocks['__call__'].assert_called_once_with(...)Helpertest_initialized_withmock.test_initialized_with() is just shortcut formock['__init__'].assert_called_once_with()
Package: unittest-parallel
unittest-parallelunittest-parallel is a parallel unit test runner for Python with coverage support.LinksSource codeRun Unit Tests in ParallelTo run unittest-parallel, specify the directory containing your unit tests with the-sargument
and your package's top-level directory using the-targument:unittest-parallel -t . -s testsBy default, unittest-parallel runs unit test modules on all CPU cores available.To run your unit tests with coverage, add either the--coverageoption (for line coverage) or the--coverage-branchfor line and branch coverage.unittest-parallel -t . -s tests --coverage-branchParallelism LevelBy default, unittest-parallel runs test modules in parallel, which works withtest class and module fixtures.
If you don't have any module fixtures, you can use the--level=classoption to run test classes in
parallel. If you don't have any module or class fixtures, you can use the--level=testoption to
run individual tests in parallel.Do I Need unittest-parallel?unittest-parallel helps the most when you have many long-running unit tests, such as those that make
web service calls or are compute-intensive. If you just have many fast-running unit tests,
unittest-parallel may slow down unit test execution due to the cost of parallelization.For example, for one of my projects with thousands of compute-intensive unit tests, running tests
with unittest-parallel isfive times fasterthan running tests using Python's built-in unit test
runner.For another project, with hundreds of fast-running unit tests, running tests using unittest-parallel
istwice as slowas running them using Python's built-in unit test runner.To determine if unittest-parallel will improve your unit test run times, you'll need to try it on
your project.DevelopmentThis package is developed usingpython-build.
It was started usingpython-templateas follows:template-specialize python-template/template/ unittest-parallel/ -k package unittest-parallel -k name 'Craig A. Hobbs' -k email 'craigahobbs@gmail.com' -k github 'craigahobbs' -k noapi 1
Package: unittest-prettify
unittest prettifyA simple module to improve theunittestoutput.Which unittest output do you prefer?If you prefer the one in the right side, this module is for you.unittest prettifyaims to be a set of tools to improve theunittestlib output.Main featuresChange the test description color in both class and method levels.Support to libraries which useunittestas bese such asDjango.Installing itpip install unittest-prettifyUsing itChanging the color for a whole test case:Thetest_1()andtest_2()will inherit the green color from the class definition.importunittestfromunittest_prettify.colorizeimport(colorize,GREEN,)@colorize(color=GREEN)classFoo(unittest.TestCase):deftest_1(self):"""This test comment should be with the Class color set as GREEN"""deftest_2(self):"""This test comment should be with the Class color set as GREEN"""Changing the color for a specific test:Thetest_1()will inherit the green color from the class definition, buttest_2()will overwrite the color by red.importunittestfromunittest_prettify.colorizeimport(colorize,GREEN,RED,)@colorize(color=GREEN)classFoo(unittest.TestCase):deftest_1(self):"""This test comment should be with the Class color set as GREEN"""@colorize(color=RED)deftest_2(self):"""This test comment should be RED"""
Package: unittest-pyspark
unittest-pysparkExtensions for testing pyspark with unittest and doctest.These utils can be used in standalone Python or in Databricks
notebooks.Usage With Doctestfromunittest_pysparkimportget_sparkspark=get_spark()defgo_spark():""">>> spark.sql("SELECT 'hello world'").show()+-----------+|hello world|+-----------+|hello world|+-----------+<BLANKLINE>>>> spark.createDataFrame([{'hello':'world'}], 'hello:string').show()+-----+|hello|+-----+|world|+-----+<BLANKLINE>"""passimportdoctestdoctest.testmod()Usage With UnittestHere is a simpleunittesttest case, which can be used as
template for pySpark test case.importunittestfromunittest_pysparkimportas_list,get_sparkimportpyspark.sql.typesaspstclassTest_Spark(unittest.TestCase):defsetUp(self):self.spark=get_spark()deftest_i_can_fly(self):input=[pst.Row(a=1,b=2)]input_df=self.spark.createDataFrame(input)expect=[{'a':1}]actual_df=input_df.select("a")actual=as_list(actual_df)self.assertEqual(actual,expect)You can find this entire example in thetests.test_samplemodule. To execute it from the command line:python-munittesttests.test_sampleUsage With Unittest and DatabricksTo execute theunittesttest cases in Databricks, add following cell:fromunittest_pyspark.unittestimport*if__name__=="__main__":execute_test_cases(discover_test_cases())Above code will automatically discover all test cases (unittest.TestCase
sub classes) defined in the global scope and execute them.Build packageYou will needsetuptoolsandtwine:pipinstall--upgradesetuptools
pipinstall--upgradewheelBuild and upload:pythonsetup.pysdistbdist_wheel
python-mtwineuploaddist/*
Package: unittestreport
unittestreport介绍1、什么是unittestreportunittestreport是基于unittest开发的的一个功能扩展库，关于unittestreport最初在开发的时候，最初只是计划开发一个unittest生成html测试报告的模块，所以起名叫做unittestreport。在开发的过程中结合使用者的反馈，慢慢的扩展了更多的功能进去。后续还会持续的扩展和开发一些新的功能，目前实现了以下功能：HTML测试报告生成unittest数据驱动测试用例失败重运行多线程并发执行用例发送测试结果及报告到邮箱测试结果推送到钉钉测试结构推送到企业微信2、安装unittestreportunittestreport是基于python3.6开发的，安装前请确认你的python版本>3.6安装命令pip install unittestreport说明：原报告模板中的CDN站点失效了，已在1.4.2版中进行了更换，如果生成的报告样式和图表丢失，请升级unittestreport版本pip install unittestreport==1.4.23、使用文档使用文档地址：https://unittestreport.readthedocs.io/en/latest/备注：开发者：柠檬班—木森E-mail:musen_nmb@qq.com大家在使用过程中发现bug,可以联系我，以便优化解决！
Package: unittest_sandbox
unittest-sandbox provides a @sandbox decorator which ensures unit test
methods do not make any socket/web requests during test execution. Note:
This currently only works with Python 3.InstallationTo install run:pip install unittest_sandboxExample usagefromunittestimportTestCaseimportrequestsfromunittest_sandboximportInternetAccessBlockedException,sandbox# The @sandbox() decorator can be applied to methods individually like belowclassRequestTests(TestCase):deftest_non_request_works(self):self.assertEqual(1+1,2)@sandbox()deftest_web_request_raises_exception_when_sandbox_decorator_is_applied(self):# If a web request is sent in a test method wrapped with the @sandbox decorator,# an InternetAccessBlockedException will be raised.withself.assertRaises(InternetAccessBlockedException):requests.get('https://www.google.com')# The @sandbox() decorator can also be applied to the class as a whole. This is the same as decorating# all 'test_' methods with @sandbox()@sandbox()classRequestTests(TestCase):deftest_non_request_works(self):self.assertEqual(1+1,2)deftest_web_request_raises_exception_when_sandbox_decorator_is_applied(self):# If a web request is sent in a test method wrapped with the @sandbox decorator,# an InternetAccessBlockedException will be raised.withself.assertRaises(InternetAccessBlockedException):requests.get('https://www.google.com')# A function can also be imported and called to prevent any web requests from occurring.# For example, this could be called at the start of a Django settings file used by the test runner to# ensure that no web requests are made by the tests.fromunittest_sandboximportblock_socket_accessblock_socket_access()
Package: unittest-templates
Unittest TemplatesWrite less unittest boilerplate.🚀 InstallationThe most recent release can be installed fromPyPIwith:$pipinstallunittest_templatesThe most recent code and data can be installed directly from GitHub with:$pipinstallgit+https://github.com/cthoyt/unittest-templates.git👐 ContributingContributions, whether filing an issue, making a pull request, or forking, are appreciated. SeeCONTRIBUTING.mdfor more information on getting involved.👋 Attribution⚖️ LicenseThe code in this package is licensed under the MIT License.🍪 CookiecutterThis package was created with@audreyfeldroy'scookiecutterpackage using@cthoyt'scookiecutter-snekpacktemplate.🛠️ For DevelopersSee developer instructionsThe final section of the README is for if you want to get involved by making a code contribution.Development InstallationTo install in development mode, use the following:$gitclonegit+https://github.com/cthoyt/unittest-templates.git
$cdunittest-templates
$pipinstall-e.🥼 TestingAfter cloning the repository and installingtoxwithpip install tox, the unit tests in thetests/folder can be
run reproducibly with:$toxAdditionally, these tests are automatically re-run with each commit in aGitHub Action.📖 Building the DocumentationThe documentation can be built locally using the following:$gitclonegit+https://github.com/cthoyt/unittest-templates.git
$cdunittest-templates
$tox-edocs
$opendocs/build/html/index.htmlThe documentation automatically installs the package as well as thedocsextra specified in thesetup.cfg.sphinxplugins
liketexextcan be added there. Additionally, they need to be added to theextensionslist indocs/source/conf.py.📦 Making a ReleaseAfter installing the package in development mode and installingtoxwithpip install tox, the commands for making a new release are contained within thefinishenvironment
intox.ini. Run the following from the shell:$tox-efinishThis script does the following:UsesBump2Versionto switch the version number in thesetup.cfg,src/unittest_templates/version.py, anddocs/source/conf.pyto not have the-devsuffixPackages the code in both a tar archive and a wheel usingbuildUploads to PyPI usingtwine. Be sure to have a.pypircfile configured to avoid the need for manual input at this
stepPush to GitHub. You'll need to make a release going with the commit where the version was bumped.Bump the version to the next patch. If you made big changes and want to bump the version by minor, you can
usetox -e bumpversion minorafter.
Package: unittest-utils
A custom module that adds some functionality to unitest (or unittest2)
python module.It adds the following:It runs the test based on the line of code where the method was defined.
Unittest order this using the method nameIt prints some color output when there is a string difference when
using assertEqual or assertEqualsHow to use itIt behaves the same as unittest2. Some from the command line to run
unittest2 use you have the following options:unittest-utils discover
unittest-utils mymodule.test.test_module
….