本文整理汇总了Python中_pytest.monkeypatch.MonkeyPatch类的典型用法代码示例。如果您正苦于以下问题:Python MonkeyPatch类的具体用法?Python MonkeyPatch怎么用?Python MonkeyPatch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MonkeyPatch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_eth_ticker
def test_eth_ticker(
empty_proxy: PaywalledProxy,
session: Session,
sender_privkey: str,
receiver_privkey: str,
monkeypatch: MonkeyPatch
):
def get_patched(*args, **kwargs):
body = {
'mid': '682.435', 'bid': '682.18', 'ask': '682.69', 'last_price': '683.16',
'low': '532.97', 'high': '684.0', 'volume': '724266.25906224',
'timestamp': '1513167820.721733'
}
return jsonify(body)
monkeypatch.setattr(PaywalledProxyUrl, 'get', get_patched)
ETHTickerProxy(receiver_privkey, proxy=empty_proxy)
ticker = ETHTickerClient(sender_privkey, session=session, poll_interval=0.5)
def post():
ticker.close()
assert ticker.pricevar.get() == '683.16 USD'
assert len(session.client.get_open_channels()) == 0
ticker.success = True
session.close_channel_on_exit = True
ticker.success = False
ticker.root.after(1500, post)
ticker.run()
assert ticker.success
示例2: _prepare
def _prepare(self):
self.counters = {}
basename = None
cli_tempdir_basename = self.config.getvalue('tempdir_basename')
if cli_tempdir_basename is not None:
basename = cli_tempdir_basename
else:
# Let's see if we have a pytest_tempdir_basename hook implementation
basename = self.config.hook.pytest_tempdir_basename()
if basename is None:
# If by now, basename is still None, use the current directory name
basename = os.path.basename(py.path.local().strpath) # pylint: disable=no-member
mpatch = MonkeyPatch()
temproot = py.path.local.get_temproot() # pylint: disable=no-member
# Let's get the full real path to the tempdir
tempdir = temproot.join(basename).realpath()
if tempdir.exists():
# If it exists, it's a stale tempdir. Remove it
log.warning('Removing stale tempdir: %s', tempdir.strpath)
tempdir.remove(rec=True, ignore_errors=True)
# Make sure the tempdir is created
tempdir.ensure(dir=True)
# Store a reference the tempdir for cleanup purposes when ending the test
# session
mpatch.setattr(self.config, '_tempdir', self, raising=False)
# Register the cleanup actions
self.config._cleanup.extend([
mpatch.undo,
self._clean_up_tempdir
])
self.tempdir = tempdir
示例3: test_setenv
def test_setenv():
monkeypatch = MonkeyPatch()
monkeypatch.setenv('XYZ123', 2)
import os
assert os.environ['XYZ123'] == "2"
monkeypatch.undo()
assert 'XYZ123' not in os.environ
示例4: test_issue1338_name_resolving
def test_issue1338_name_resolving():
pytest.importorskip("requests")
monkeypatch = MonkeyPatch()
try:
monkeypatch.delattr("requests.sessions.Session.request")
finally:
monkeypatch.undo()
示例5: test_undo_class_descriptors_delattr
def test_undo_class_descriptors_delattr():
class SampleParent(object):
@classmethod
def hello(_cls):
pass
@staticmethod
def world():
pass
class SampleChild(SampleParent):
pass
monkeypatch = MonkeyPatch()
original_hello = SampleChild.hello
original_world = SampleChild.world
monkeypatch.delattr(SampleParent, "hello")
monkeypatch.delattr(SampleParent, "world")
assert getattr(SampleParent, "hello", None) is None
assert getattr(SampleParent, "world", None) is None
monkeypatch.undo()
assert original_hello == SampleChild.hello
assert original_world == SampleChild.world
示例6: test_setitem_deleted_meanwhile
def test_setitem_deleted_meanwhile():
d = {}
monkeypatch = MonkeyPatch()
monkeypatch.setitem(d, "x", 2)
del d["x"]
monkeypatch.undo()
assert not d
示例7: test_issue156_undo_staticmethod
def test_issue156_undo_staticmethod(Sample):
monkeypatch = MonkeyPatch()
monkeypatch.setattr(Sample, "hello", None)
assert Sample.hello is None
monkeypatch.undo()
assert Sample.hello()
示例8: test_client_private_key_path
def test_client_private_key_path(
patched_contract,
monkeypatch: MonkeyPatch,
sender_privkey: str,
tmpdir: LocalPath,
web3: Web3,
channel_manager_address: str
):
def check_permission_safety_patched(path: str):
return True
monkeypatch.setattr(
microraiden.utils.private_key,
'check_permission_safety',
check_permission_safety_patched
)
privkey_file = tmpdir.join('private_key.txt')
privkey_file.write(sender_privkey)
with pytest.raises(AssertionError):
Client(
private_key='0xthis_is_not_a_private_key',
channel_manager_address=channel_manager_address,
web3=web3
)
with pytest.raises(AssertionError):
Client(
private_key='0xcorrect_length_but_still_not_a_private_key_12345678901234567',
channel_manager_address=channel_manager_address,
web3=web3
)
with pytest.raises(AssertionError):
Client(
private_key='/nonexisting/path',
channel_manager_address=channel_manager_address,
web3=web3
)
Client(
private_key=sender_privkey,
channel_manager_address=channel_manager_address,
web3=web3
)
Client(
private_key=sender_privkey[2:],
channel_manager_address=channel_manager_address,
web3=web3
)
Client(
private_key=str(tmpdir.join('private_key.txt')),
channel_manager_address=channel_manager_address,
web3=web3
)
示例9: test_setenv
def test_setenv():
monkeypatch = MonkeyPatch()
with pytest.warns(pytest.PytestWarning):
monkeypatch.setenv("XYZ123", 2)
import os
assert os.environ["XYZ123"] == "2"
monkeypatch.undo()
assert "XYZ123" not in os.environ
示例10: test_context
def test_context():
monkeypatch = MonkeyPatch()
import functools
import inspect
with monkeypatch.context() as m:
m.setattr(functools, "partial", 3)
assert not inspect.isclass(functools.partial)
assert inspect.isclass(functools.partial)
示例11: pytest_configure
def pytest_configure(config):
"""Create a TempdirFactory and attach it to the config object.
This is to comply with existing plugins which expect the handler to be
available at pytest_configure time, but ideally should be moved entirely
to the tmpdir_factory session fixture.
"""
mp = MonkeyPatch()
t = TempdirFactory(config)
config._cleanup.extend([mp.undo, t.finish])
mp.setattr(config, '_tmpdirhandler', t, raising=False)
mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
示例12: test_setenv_deleted_meanwhile
def test_setenv_deleted_meanwhile(before):
key = "qwpeoip123"
if before:
os.environ[key] = "world"
monkeypatch = MonkeyPatch()
monkeypatch.setenv(key, "hello")
del os.environ[key]
monkeypatch.undo()
if before:
assert os.environ[key] == "world"
del os.environ[key]
else:
assert key not in os.environ
示例13: pytest_configure
def pytest_configure(self, config):
if not config.getoption('ast_as_python'):
return
mp = MonkeyPatch()
mp.setattr(
'_pytest.assertion.rewrite.rewrite_asserts',
make_replacement_rewrite_asserts(self.store))
# written pyc files will bypass our patch, so disable reading them
mp.setattr(
'_pytest.assertion.rewrite._read_pyc',
lambda source, pyc, trace=None: None)
config._cleanup.append(mp.undo)
示例14: block_unmocked_requests
def block_unmocked_requests():
"""
Prevents requests from being made unless they are mocked.
Helps avoid inadvertent dependencies on external resources during the test run.
"""
def mocked_send(*args, **kwargs):
raise RuntimeError('Tests must mock all HTTP requests!')
# The standard monkeypatch fixture cannot be used with session scope:
# https://github.com/pytest-dev/pytest/issues/363
monkeypatch = MonkeyPatch()
# Monkeypatching here since any higher level would break responses:
# https://github.com/getsentry/responses/blob/0.5.1/responses.py#L295
monkeypatch.setattr('requests.adapters.HTTPAdapter.send', mocked_send)
yield monkeypatch
monkeypatch.undo()
示例15: test_setenv_prepend
def test_setenv_prepend():
import os
monkeypatch = MonkeyPatch()
monkeypatch.setenv('XYZ123', 2, prepend="-")
assert os.environ['XYZ123'] == "2"
monkeypatch.setenv('XYZ123', 3, prepend="-")
assert os.environ['XYZ123'] == "3-2"
monkeypatch.undo()
assert 'XYZ123' not in os.environ