Saravanan666/pypi-org huggingface dataset:
Package: mockfly-python-sdk
mockfly-python-sdkSDK DocumentationGeneral Overview:Themockfly-python-sdkSDK provides a simple interface to interact with the Mockfly service. The SDK allows you to identify users and retrieve flags based on a user's evaluation key.Getting Started:To begin usingmockfly-python-sdk, you need to install it. (Note: I'm assuming that the package is available on PyPI).pipinstallmockfly-python-sdkThen, you can import it into your project:frommockflyimportMockflyConstructor:The SDK is initialized using the constructor. The constructor accepts the following parameters:environment: The environment for which you are obtaining the flags: "production" or "test".auth_header: A string representing the authorization header required to make calls to the Mockfly API. This should be derived from your project's private API key.Example:mockfly=Mockfly(environment='production',auth_header='YOUR_PRIVATE_API_KEY',)Methods:identify(value)This method is used to identify a user within the system.value: The user's evaluation key. It is essential to call this method beforeget_flag().Example:mockfly.identify('user@gmail.com')get_flag(key)This method is used to get a flag based on the provided key.key: The key of the flag you wish to get.Returns a dictionary that represents the flag value for the given key and the identified user.Example:try:data=mockfly.get_flag('feature_toggle')print(data)exceptExceptionaserror:print(error)Error Handling:The SDK has built-in validations and will raise errors in the following cases:If theauth_headeris not provided when creating aMockflyinstance.If attempting to get a flag without providing a key.If attempting to get a flag without previously identifying the user.Conclusion:Themockfly-python-sdkSDK simplifies interaction with the Mockfly service from Python applications. Ensure to handle potential errors and use theidentifymethod before making calls toget_flag. Always remember that theauth_headervalue should be derived from the private API key of your project.
Package: mockgen
foundation *Beta*================A foundation made with cementPlease ★ this repo if you found it useful ★ ★ ★Features---------  Controllers-  ServicesDependencies-------------  `Python`_Support-------Submit an `issue`_Buy Me Coffee-------------A ridiculous amount of coffee was consumed in the process of buildingthis project.`Add some fuel`_ if you’d like to keep me going!Contributing------------1. Fork it!2. Create your feature branch: ``git checkout -b my-new-feature``3. Commit your changes: ``git commit -m 'Add some feature'``4. Push to the branch: ``git push origin my-new-feature``5. Submit a pull request :DLicense-------`MIT License`_`Jam Risser`_ © 2017Credits--------  `Jam Risser`_ - AuthorChangelog---------0.1.0 (2017-08-27)-  Beta release.. _Python: https://www.python.org/.. _issue: https://github.com/jamrizzi/foundation/issues/new.. _Add some fuel: https://pay.jamrizzi.com.. _MIT License: https://github.com/jamrizzi/foundation/blob/master/LICENSE.. _Jam Risser: https://jamrizzi.com
Package: mockie
Helper classes for easier mocking and patching tests.SamplefrommockieimportTestCasefrommyimportmoduleclassMyTest(TestCase):defsetUp(self):self.mock_shutil=self.patch("my.module.shutil")deftest_my_function_with_side_effects(self):module.function()self.mock_shutil.rmtree.assert_called_once_with("my_file.txt")APITestCaseself.Mockself.MagicMockself.patchself.patch_objectself.patch_multipleself.patch_dictself.mock_openself.assertCalledself.assertCalledOnceWithself.assertAnyCallself.assertIsMockedself.assertIsMockself.assertIsMagicMockLicense (MIT)The MIT License (MIT)Copyright (c) 2015marcwebbie.Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Package: mockify
MockifyHighly customizable and expressive mocking library for Python.AboutMockify is a library inspired by Google Mock C++ framework, but adopted to
Python world.Mockify is based onexpectationsthat you need to record on your mocksbeforethose are called by code you're testing. And expectations you're
recording are basically assertions that must pass before test ends. Along
with expectations you can also record actions the mock will execute once
called. And all of these is provided by simple, expressive and easy to use
API.Here's a simple example:frommockify.coreimportsatisfiedfrommockify.mockimportMockfrommockify.actionsimportReturndeffunc_caller(func):returnfunc()deftest_func_caller():func_mock=Mock('greet')func_mock.expect_call().will_once(Return('Hello, world!'))withsatisfied(func_mock):assertfunc_caller(func_mock)=='Hello, world!'Mockify allows you to:Record expectations with any number of positional and/or keyword arguments,Set expected call count or call count range,Recordaction chains, allowing subsequent action can be performed on
subsequent call to same mock,Recordrepeatedactions that can be executed any number of times,Usematchers, allowing to match range of parameters the mock is called
with instead of exact ones,and more.I hope you'll find this library useful.DocumentationNewest documentation can be found athttps://mockify.readthedocs.org/.SourceSource code is available athttps://gitlab.com/zef1r/mockify/.LicenseThis software is released under the terms of the MIT license.
Package: mock-import
A helper mocking function to maskImportErrors on a scoped code.
Failed imports will be ignored, unless specified by thedo_not_mockargument.InstallationUsing pip:pip installmock-importUsageImport:>>> from mock_import import mock_importMocking import for a code block:>>> with mock_import():
...     import no_such_module  # Won't raise ImportError
...     no_such_module.no_such_function()  # Won't raise AttributeErrorMocking import as a decorator:>>> @mock_import()
... def method():
...     import no_such_module  # Won't raise ImportError
...     no_such_module.no_such_function()  # Won't raise AttributeError>>>     import no_such_module  # raises ImportErrorMaking an exception:>>> with mock_import(do_not_mock='no_such_module'):
...     import no_such_other_module  # Won't raise ImportError
...     import no_such_module  # Will raise ImportError>>> with mock_import(do_not_mock=['nsm1', 'nsm2']):
...     import nsm  # Won't raise ImportError
...     import nsm1  # Will raise ImportError
...     import nsm2  # Will raise ImportError
Package: mockingbird-psd
MockingbirdTL;DR - Key FeaturesUses Photoshop documentsSupports Bulk-EditSupports single and multi-frame mockupsSupports transparencySupports resizing (aspect fit)Supports Multicore SystemsThe Long StoryThis tool helps you to embed your app screenshots inside Apples device mockups.
Because the script reads the original photoshop documents Apple provides within their marketing guidelines, there is no need to wait for updates of the library after new product releases.
Multi-Frame Mockups, e.g. one containing iPad and iPhone, are supported.InstallationThe only prerequisite is Python 3.6 or higher. On macOS its comfy to install it via homebrew, i.e.brew install python3.
To install mockingbird, usepip3 install mockingbird-psd.InstructionsYour screenshots need to be organized into folders.
Each folder represents one device and contains the screenshots for every feature you wish to showcase.
The folders are specified using the--screenshotsparameter.
Concerning the layers of the photoshop document, the folders should be given from background to foreground.You might also want to have a look at the usage messagemockingbird --helpSingle-Frame mockups:mockingbird --frame ./iphone_11.psd --screenshots ./iphone11Multi-Frame mockups:mockingbird --frame ./ipad_iphone.psd --screenshots ./ipad129inch ./iphone11This command uses the dual-device psd file and combines it with the images from./ipad129inchin the background device and./iphone11in the foreground device.
Package: mockingjay
A simple library to build mock http services based on HTTPrettyFree software: BSD licenseDocumentation:https://mockingjay.readthedocs.org.FeaturesProvides a fluent interface for building service mocks using HTTPrettyAllows mocking of response body using templated fixturesHistory0.1.1 (2015-05-25)Addedshould_return_jsonbuilder methodMock response status code0.1.0 (2015-05-23)First release on PyPI.
Package: mocking-utils
mocking-utilsHighly useful utilities for mocking execution flow during unit test execution.Quick StartInstallationpip install mocking-utilsUsagefrom mocking_utils import MockFunction

class A(object):
    def my_method(self):
        print('I am in my_method')

a = A()
a.my_method()  # Out: 'I am in my_method'
mock = MockFunction(A, 'my_method', lambda x: print('lambda function'), call=True)
a.my_method()  # Out: 'lambda function'
mock.reset()
a.my_method()  # Out: 'I am in my_method'Examplespytestfrom mocking_utils import MockFunction

@pytest.fixture(scope='module', autouse=True)
def setup__teardown():
    """
    Standard setup & teardown within a module of unit tests.
    """
    mocks = [
        MockFunction(A, 'my_method', lambda x: print('lambda function'), call=True)
        ]
    yield 'Setup complete'
    [mock.reset() for mock in mocks]Testing & Code QualityCode coverage reports for master, branches, and PRs
are postedhere in CodeCov.
Package: mockish
mockishA thin layer of sugar atop Python's mock.LinksCode Repohttps://www.github.com/fresh2dev/mockishMirror Repohttps://www.f2dv.com/code/r/mockishDocumentationhttps://www.f2dv.com/code/r/mockish/iChangeloghttps://www.f2dv.com/code/r/mockish/i/changelogLicensehttps://www.f2dv.com/code/r/mockish/i/licenseFundinghttps://www.f2dv.com/fundOverviewmockishis a small tool I built to make life easier when writing tests in Python.It provides:Explicit alternatives to the nuancedmock.Mock(side_effect=...)argument, including:mockish.Mock(return_value=...)mockish.Mock(return_call=...)mockish.Mock(return_once=...)mockish.Mock(return_each=...)mockish.Mock(return_exception=...)Methods for creating HTTP responses -- bothrequests.Responseandhttpx.Responseobjects -- that can be returned by the Mock, including:mockish.httpx.Response.from_dict(...)mockish.requests.Response.from_dict(...)InstallFromPyPi{:target="_blank"}:pipinstallmockishUseComplete example of mocking a HTTP response:frommockishimportMock,patchfrommockish.requestsimportResponseimportrequestsmock_resp=Response.from_dict({'hello':'world'})withpatch.object(requests,'get',Mock(return_once=mock_resp)):resp:requests.Response=requests.get('https://www.fresh2.dev')requests.get.assert_called_once()print(resp)><Response[200]>print(resp.json())>{'hello':'world'}See the reference docs for more examples:mockish.Mockmockish.httpx.Responsemockish.requests.ResponseSupportIf this project delivers value to you, pleaseprovide feedback, code contributions, and/orfunding.
Package: mockito
Mockito is a spying framework originally based onthe Java library with the same name.Installpip install mockitoQuick Start90% use case is that you want to stub out a side effect.from mockito import when, mock, unstub

when(os.path).exists('/foo').thenReturn(True)

# or:
import requests  # the famous library
# you actually want to return a Response-like obj, we'll fake it
response = mock({'status_code': 200, 'text': 'Ok'})
when(requests).get(...).thenReturn(response)

# use it
requests.get('http://google.com/')

# clean up
unstub()Read the docshttp://mockito-python.readthedocs.io/en/latest/Run the testspip install pytest
py.test
Package: mock_matchers
mock.matchers simply makesPyHamcrestmatchers usable with themockassertion calls.Examples:from mock import Mock
import mock_matchers

m = Mock()
m.foo(1,2,3)
m.bar([1,2,3])

m.foo.assert_called_with(
    mock_matchers.instance_of(int),
    mock_matchers.instance_of(int),
    3
)
m.foo.assert_called_with(
    [
                    mock_matchers.instance_of(int),
                    2,
                    3
    ]
)
m.foo.assert_called_with(mock_matchers.isntance_of(list))etc… For a full list of available matchers refer to thePyHamcrest Matchersdocumentation and simply replacefrom hamcrest import <name_of_matcher>withfrom mock_matchers import <name_of_matcher>
Package: mock-open
mock-openA better mock for file I/O.Install$ pip install mock-openclassMockOpenTheMockOpenclass should work as a stand-in replacement formock.mock_openwith
some added features (though it tries to conform to how the builtinopenworks where the two
differ):Multiple file support, including a mapping-like access to file mocks by path:frommock_openimportMockOpenmock_open=MockOpen()mock_open["/path/to/file"].read_data="Data from a fake file-like object"mock_open["/path/to/bad_file"].side_effect=IOError()You can also configure behavior via the regularmocklibrary API:mock_open=MockOpen()mock_open.return_value.write.side_effect=IOError()Persistent file contents between calls toopen:withpatch("builtins.open",MockOpen()):withopen("/path/to/file","w")ashandle:handle.write("Some text")withopen("/path/to/file","r")ashandle:assert"Some text"==handle.read()All the regular file operations:read,readline,readlines,write,writelines,seek,tell.AcknowledgementsThis library uses modified versions of tests from theCPython source codeas part of its
test suite. The original tests are licensed under thePSF license agreementand are
copyright of the Python Software Foundation.
Package: mockprocess
MockProcess is a mock for the subprocess module to be used in your unit tests.
Right now it only supports the check_output method, but eventually popen will
be supported as well.It is used via a context manager.  Here’s a basic example>>> import subprocess
>>> import unittest
>>> from mockprocess import MockCheckOutput
>>> class Test(unittest.TestCase):
...     def test_simple(self):
...         with MockCheckOutput('hello\n'):
...             output = subprocess.check_output(['/bin/echo', 'hello'])
...         self.assertEqual(output, 'hello\n')
...If you need to test how you handle errors, you can set an exit code as well.>>> import subprocess
>>> import unittest
>>> from mockprocess import MockCheckoutput
>>> class Test(unittest.TestCase):
...     def test_exception(self):
...         try:
...             with MockCheckOutput('hello\n', exit_code=127):
...                 subprocess.check_output(['/bin/false'])
...         except subprocess.CalledProcessError as exp:
...             pass
...         else:
...             self.fail('exception was not raised')
Package: mock-protocol
mock_protocolA unittest mock library than understands protocols and annotationsA drop-in replacement for the builtin python 3.7 unittest.mock module where annotations on spec objects are used to spec mocked attributes and methods.In addition to the standardunittest.mockfunctionality, a newfrom_protocolfunction
is added.importmock_protocolm=mock_protocol.from_protocol(C,**kwargs)is an alias form=mock_protocol.create_autospec(C,spec_set=True,instance=True,**kwargs)which is essentially the same as theunittest.mockmethod of the same namem=unittest.mock.create_autospec(C,spec_set=True,instance=True,**kwargs)except that type-hints are used to spec the mocked attributes.When you have type-hinted code like thisclassA(object):b:strdef__init__(self,b:str):self.b=bdeffoo(self,bar:int)->list:return['x']*barclassC(object):a:intdef__init__(self,a:int):self.a=adefbar(self,foo:str)->A:returnA(foo)Then mocking them with mock_protocol will use the type hints as specs for child mocks.m=mock_protocol.from_protocol(C)a=m.bar('hello')# the following are all Trueisinstance(a,A)isinstance(a.b,str)isinstance(m.a,int)isinstance(a.foo(4),list)mock_protocolalso understands commontypingtypes such asDictandTupleandOptionalimporttypingclassD(object):a:typing.Optional[int]d:typing.Dict[str,int]e:typing.Optional[typing.AnyStr]t:typing.Tuple[int,float]def__init__(self,a:int):self.a=adefbar(self,foo:str)->typing.Optional[A]:returnA(foo)m=mock_protocol.from_protocol(D)a=m.bar('hello')# the following are all Trueisinstance(m,D)isinstance(a,A)isinstance(m.a,int)isinstance(m.d,dict)isinstance(m.e,str)isinstance(m.t,tuple)
Package: mockpy
# Mockpy[![Build Status](https://travis-ci.org/oarrabi/mockpy.svg?branch=master)](https://travis-ci.org/oarrabi/mockpy)Mockpy is a python open source line utility to quickly create mock servers on Mac OS X.Mockpy is inspired by wiremock and uses libmproxy for the proxy functionality.mockpy works by reading a list of configuration files in the YAML format, it uses these configurations to match the http request received and return an http response based on the matched YAML file configuration.# Why mockpy- You want a very lightweight utility to quickly create a mock API- No need to edit your app code as it uses proxy mocking- Works on top of proven technology ([mitmproxy](https://mitmproxy.org/) and [cherrypi](http://www.cherrypy.org/))- Update to the mock API are picked up from files without the need to start/restart the server again.# InstallationMockpy can be installed as a python wheel using `pip` or as a standalone binary using `homebrew`## Installing with pipMake sure you have [pip](https://pip.pypa.io/en/latest/installing.html) installed.Run the following to install mockpypip install mockpy## Installing using brewInstall using brew tapbrew tap oarrabi/tapbrew install mockpy# UsageBellow is a description of the basic operations that `mockpy` provides, for a more complete understanding please refer to [the wikis](https://github.com/oarrabi/mockpy/wiki).## Initialize a directoryInitialize a the current folder by running:mockpy initThis will create two folders:`inout`: this folder will contains a list of mapping YAML files, each YAML file represents an request and response operation.`res`: resource folder contains the static HTML, JSON, Images and static files returned as part of the mocking process.To understand the YAML file format, please refer to the documentation.## Start the mock serverThe mock server can be started as a standalone web server, or as a proxy server.### Standalone web serverUse `mockpy start` to start the standalone web server, this will setup a server on the default port. Visit `127.0.0.1:9090` to check the mock server.### Proxy web serverTo start mockpy in proxy server mode use `mockpy start -x`. This command does the following:- Starts a proxy server on '127.0.0.1:9090'- Sets the macs HTTP/HTTPS settings to the created proxy server.History-------0.1.0 (2015-01-11)---------------------* First release on PyPI.
Package: mockquerpy
MockQuerPyThis project implements a mocking library for quick and easy testing of google
bigquery based python projectsGetting startedInstructions on getting a local developement copy on your machineUsing the Lib in your projectBasic use:$ pip install mockquerpyUse either the context manager or decorator in your tests:frommockquerpyimportMockQuerPy,mockquerpy_wrapwithMockQuerPy(TEST_DATA)asbigquery:print('bigquery inside here is a mockobject')@mockquerpy_wrapdeftest_my_bq_implementation(bigquery):print('bigquery inside here is a mockobject')MockQuerPy.set_test_data(MY_TEST_DATA)See the projectdocumentationfor more // TODODeveloping the libraryPrereqPython 3.7 or higherInstructionsDeveloping the library:Set up a python virtualenv$ virtualenv venv && source venv/bin/activateInstall the dependencies$ pip install -r requirements.txtTestingProject is being tested using the pytest framework. This is also added to the
CI pipeline.$ pytest .DeployingDeployment is and should be handled by the CD pipeline to the project, but can
be done manually:
Package: mockr
mockrmockr is a Python library for writing MapReduce jobs in an Educational setting. It is intended to be used as a
conceptual teaching tool.mockr provides an interface for defining and running MapReduce locally. Simply define your map and reduce functions,
input your data and call the run function. Everything is run sequentially and locally.Installationpip install mockrDocumentationFull documentation available herehttps://mockr.readthedocs.io/Streaming JobsStreamingJob class which expects the input to be a byte stream of characters. The chunks of data are separated by
newline ("\n") characters. Each line is sent to a separate map worker.Native Python Sequence JobsPythonJob class expects input to be a Collections.abc.Sequence type object e.g. Python List. Python Jobs provide two
exection methods:the sequence is divided into chunks and each chunk is sent to a separate map workereach item in the list is individually sent to a dedicated map workerPandas JobsPandasJob class expects input to be a Pandas DataFrame. The rows of the data frame are equally divided into chunks and
each chunk is sent to a separate map workerExample Usageimport re
from mockr import run_stream_job

WORD_RE = re.compile(r"[\w']+")

def map_fn(chunk):
    # yield each word in the line
    for word in WORD_RE.findall(chunk):
        yield (word.lower(), 1)

def reduce_fn(key, values):
    yield (key, sum(values))

input_str = "Hello!\nThis is a sample string.\nIt is very simple.\nGoodbye!"

results = run_stream_job(input_str, map_fn, reduce_fn)

print(results)Output:[('hello', 1), ('this', 1), ('is', 2), ('a', 1), ('sample', 1), ('string', 1), ('it', 1), ('very', 1), ('simple', 1), ('goodbye', 1)]
Package: mockrdd
mockrddA Python3 module for testing PySpark code.The MockRDD class offers similar behavior topyspark.RDDwith the following
extra benefits.Extensive sanity checks to identify invalid inputsMore meaningful error messages for debugging issuesStraightforward to running within pdbRemoves Spark dependencies from development and testing environmentsNo Spark overhead when running through a large test suiteSimple example of using MockRDD in a test.frommockrddimportMockRDDdefjob(rdd):returnrdd.map(lambdax:x*2).filter(lambdax:x>3)assertjob(MockRDD.empty()).collect()==[]assertjob(MockRDD.of(1)).collect()==[]assertjob(MockRDD.of(2)).collect()==[4]Conventionally, you'd include a main method to hook the RDD up to product sources and sinks.
Further, the testing would be included in a separate file and use the moduleunittestfor defining test cases.See the docstring ofmockrdd.MockRDDfor more information.
Package: mockry
mockryA simple but rich mock HTTP server you have searched for.Easy to start.Get the docker package and start hacking in a minutes.Easy to use.Create a simple JSON with your mock data and pass it as param to mockry.Rich.Parse input CSV, convert it to JSON, send it at some URL and return the combined result? It's just a small things mockry can do for you. No programming required.InstallationDockermockery should be used as a standalone application inside a Docker container.Pull the official image from Docker Hub:$dockerpullglibin/mockry:latest
$dockerrun-p7777:7777-itglibin/mockryTo use your custom schema create and editapplication.jsonfile and link containing directory to your container:$dockerrun-p7777:7777-v/path/to/application/json/dir:/data-itglibin/mockryOr you can build your own image:$dockerbuild-tmockry.
$dockerrun-p7777:7777-itmockryFrom the sourcePython 3.7+ is required to run mockry. You can install it frompython.orgor with your OS package manager.$python3.7-mvenv.venv
$source.venv/bin/activate
$pipinstall-rrequirements.txt
$python-mmockryPossible options:OptionDescriptionDefault--host=<host>Host to bind the server127.0.0.1--port=<port>Port to bind the server7777--json=<path_to_json>Path to application json fileapplication.json--debug=<mode>Debug mode (iftruethe changes in application json file would be automatically applied)true--helpShow all available options