本文整理汇总了Python中twisted.python.monkey.MonkeyPatcher类的典型用法代码示例。如果您正苦于以下问题:Python MonkeyPatcher类的具体用法?Python MonkeyPatcher怎么用?Python MonkeyPatcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MonkeyPatcher类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_delete_works_on_valid_credentials
def test_delete_works_on_valid_credentials(self):
from hashlib import sha512
ctuple = namedtuple('named_user', 'email key')
user_tuple = ctuple('[email protected]', sha512('key').hexdigest())
def delete(fles, user):
self.assertEqual(user.email, '[email protected]')
self.assertEqual(user, user_tuple)
monkey_patcher = MonkeyPatcher((user.User, 'delete', delete))
monkey_patcher.patch()
url = '/delete/key'
request = self.generate_request_and_session(
url, auth=lambda: True, uuid='73s7b33f'
)
request.session.user = user_tuple
request.session.expire = lambda: True
result = yield self.account.render(request)
self.assertEqual(result.code, http.OK)
self.assertEqual(result.subject['success'], True)
示例2: __init__
def __init__(self, model):
if '__pypy__' in sys.modules:
# try to use psycopg2ct if we are on PyPy
try:
from psycopg2ct import compat
compat.register()
# monkey patch to dont let Storm crash on register type
import psycopg2
psycopg2._psycopg = object
class _psycopg:
UNICODEARRAY = psycopg2.extensions.UNICODEARRAY
from twisted.python.monkey import MonkeyPatcher
monkey_patcher = MonkeyPatcher(
(psycopg2, '_psycopg', _psycopg))
monkey_patcher.patch()
except ImportError:
raise RuntimeError(
'You are trying to use PostgreSQL with PyPy. Regular '
'psycopg2 module don\'t work with PyPy, you may install '
'psycopg2ct in order to can use psycopg2 with PyPy'
)
self.model = model
示例3: test_constructWithPatches
def test_constructWithPatches(self):
"""
Constructing a L{MonkeyPatcher} with patches should add all of the
given patches to the patch list.
"""
patcher = MonkeyPatcher((self.testObject, "foo", "haha"), (self.testObject, "bar", "hehe"))
patcher.patch()
self.assertEqual("haha", self.testObject.foo)
self.assertEqual("hehe", self.testObject.bar)
self.assertEqual(self.originalObject.baz, self.testObject.baz)
示例4: test_put_verifyProperRemoval
def test_put_verifyProperRemoval(self):
# Replace the time function of the datastore module
# so that we can artificially speed up time
monkey_patcher = MonkeyPatcher()
c = clock()
c.set(0)
monkey_patcher.addPatch(datastore, "time", c)
# Replace the peer_timeout to 5 seconds
monkey_patcher.addPatch(constants, "peer_timeout", 5)
monkey_patcher.patch()
# Insert a node and verify it is within the datastore
m = self.datastore(self.reactor)
infohash = 5
expected_peer = ("127.0.0.1", 5151)
m.put(infohash, expected_peer)
peers = m.get(infohash)
# Iterate over a 1 element list
for peer in peers:
self.assertEqual(expected_peer, peer)
self.assertEquals(1, len(peers))
# Change the time and verify that the cleaning function
# actually removes the peer
c.set(5)
# TODO hackish, shouldnt reach into object
m._cleanup(infohash, peer)
peers = m.get(infohash)
self.assertEqual(0, len(peers))
monkey_patcher.restore()
示例5: test_constructWithPatches
def test_constructWithPatches(self):
"""
Constructing a L{MonkeyPatcher} with patches should add all of the
given patches to the patch list.
"""
patcher = MonkeyPatcher((self.testObject, 'foo', 'haha'),
(self.testObject, 'bar', 'hehe'))
patcher.patch()
self.assertEqual('haha', self.testObject.foo)
self.assertEqual('hehe', self.testObject.bar)
self.assertEqual(self.originalObject.baz, self.testObject.baz)
示例6: test_metadata_service
def test_metadata_service(self):
"""
The instance ID is retrieved from the metadata service if it can't be
found on the config drive.
"""
patch = MonkeyPatcher()
# A compute_instance_id found from the metadata service
server_compute_instance_id = unicode(uuid4())
# Point the API to a config drive label that won't be found.
configdrive_label = filesystem_label_for_test(self)
patch.addPatch(
self.api,
'_config_drive_label',
configdrive_label,
)
# Set up a fake metadata service and point the API to its endpoint
listening = webserver_for_test(
self,
url_path="/" + "/".join(METADATA_RELATIVE_PATH),
response_content=json.dumps(
{"uuid": server_compute_instance_id}
),
)
def set_metadata_service_endpoint(port):
address = port.getHost()
endpoint = (address.host, address.port)
patch.addPatch(
self.api,
'_metadata_service_endpoint',
endpoint,
)
return port
listening.addCallback(set_metadata_service_endpoint)
# Run compute_instance_id in a separate thread.
# With the API patched to check the fake metadata sources.
def start_compute_instance_id(port):
patch.patch()
return deferToThread(
self.api.compute_instance_id
)
connecting = listening.addCallback(start_compute_instance_id)
def check(result):
self.assertEqual(server_compute_instance_id, result)
checking = connecting.addCallback(check)
return checking
示例7: __init__
def __init__(self, model):
if '__pypy__' in sys.modules:
# try to use psycopg2ct if we are on PyPy
try:
from psycopg2ct import compat
compat.register()
# monkey patch to dont let Storm crash on register type
import psycopg2
psycopg2._psycopg = object
class _psycopg:
UNICODEARRAY = psycopg2.extensions.UNICODEARRAY
from twisted.python.monkey import MonkeyPatcher
monkey_patcher = MonkeyPatcher(
(psycopg2, '_psycopg', _psycopg))
monkey_patcher.patch()
except ImportError:
raise RuntimeError(
'You are trying to use PostgreSQL with PyPy. Regular '
'psycopg2 module don\'t work with PyPy, you may install '
'psycopg2ct in order to can use psycopg2 with PyPy'
)
self.model = model
self._columns_mapping = {
properties.Bool: 'bool',
properties.UUID: 'uuid',
properties.RawStr: 'bytea',
properties.Pickle: 'bytea',
properties.JSON: 'json',
properties.DateTime: 'timestamp',
properties.Date: 'date',
properties.Time: 'time',
properties.TimeDelta: 'interval',
properties.Enum: 'integer',
properties.Decimal: 'decimal'
}
self.parse = singledispatch(self.parse)
self.parse.register(properties.Int, self._parse_int)
self.parse.register(properties.Unicode, self._parse_unicode)
self.parse.register(properties.Float, self._parse_float)
self.parse.register(properties.List, self._parse_list)
self.parse.register(NativeEnum, self._parse_enum)
示例8: setUp
def setUp(self):
self.monkey_patcher = MonkeyPatcher()
self.monkey_patcher.addPatch(krpc_sender, "reactor", HollowReactor())
self.monkey_patcher.patch()
self.k_iter = KRPC_Iterator()
self.k_iter.transport = HollowTransport()
self.target_id = 5
示例9: _monkey_patch
def _monkey_patch(self):
"""
Monkeypatch some parts of the twisted library that are waiting
for bugfix inclussion in the trunk
"""
if not self.monkey_patched:
# add new method
setattr(http.Request, 'getClientProxyIP', getClientProxyIP)
# patch getClientIP
monkey_patcher = MonkeyPatcher(
(http.Request, 'getClientIP', getClientIPPatch)
)
monkey_patcher.patch()
self.monkey_patched = True
示例10: test_error_logging
def test_error_logging(self, logger):
"""
Failures while applying a diff emit a log message containing the full
diff.
"""
o1 = DiffTestObjInvariant(
a=1,
b=2,
)
patcher = MonkeyPatcher()
patcher.addPatch(
DiffTestObjInvariant,
'_perform_invariant_check',
False
)
patcher.patch()
try:
o2 = o1.set('b', 1)
finally:
patcher.restore()
diff = create_diff(o1, o2)
self.assertRaises(
InvariantException,
diff.apply,
o1,
)
示例11: test_exclude_from_tilde_expansion
def test_exclude_from_tilde_expansion(self):
basedir = "cli/Backup/exclude_from_tilde_expansion"
fileutil.make_dirs(basedir)
nodeurl_path = os.path.join(basedir, 'node.url')
fileutil.write(nodeurl_path, 'http://example.net:2357/')
# ensure that tilde expansion is performed on exclude-from argument
exclude_file = u'~/.tahoe/excludes.dummy'
ns = Namespace()
ns.called = False
def call_file(name, *args):
ns.called = True
self.failUnlessEqual(name, abspath_expanduser_unicode(exclude_file))
return StringIO()
patcher = MonkeyPatcher((__builtin__, 'file', call_file))
patcher.runWithPatches(parse_options, basedir, "backup", ['--exclude-from', unicode_to_argv(exclude_file), 'from', 'to'])
self.failUnless(ns.called)
示例12: test_regsiter_works_when_provided_information_is_valid
def test_regsiter_works_when_provided_information_is_valid(self):
def create(fles):
self.assertEqual(fles.name, 'Someone')
self.assertEqual(fles.email, '[email protected]')
monkey_patcher = MonkeyPatcher((user.User, 'create', create))
monkey_patcher.patch()
request = self.generate_request(['/register'], '''{
"name": "Someone",
"email": "[email protected]"
}''')
result = yield self.account.render(request)
self.assertEqual(result.code, http.OK)
self.assertEqual(type(result.subject), dict)
self.assertEqual(result.headers['content-type'], 'application/json')
self.assertTrue(result.subject['success'])
示例13: test_report_import_error
def test_report_import_error(self):
marker = "wheeeyo"
real_import_func = __import__
def raiseIE_from_this_particular_func(name, *args):
if name == "foolscap":
raise ImportError(marker + " foolscap cant be imported")
else:
return real_import_func(name, *args)
# Let's run as little code as possible with __import__ patched.
patcher = MonkeyPatcher((__builtin__, "__import__", raiseIE_from_this_particular_func))
vers_and_locs, errors = patcher.runWithPatches(allmydata.get_package_versions_and_locations)
foolscap_stuffs = [stuff for (pkg, stuff) in vers_and_locs if pkg == "foolscap"]
self.failUnlessEqual(len(foolscap_stuffs), 1)
comment = str(foolscap_stuffs[0][2])
self.failUnlessIn(marker, comment)
self.failUnlessIn("raiseIE_from_this_particular_func", comment)
self.failUnless([e for e in errors if "dependency 'foolscap' could not be imported" in e])
示例14: test_regsiter_works_when_provided_information_is_valid
def test_regsiter_works_when_provided_information_is_valid(self):
def create(fles):
self.assertEqual(fles.name, "Someone")
self.assertEqual(fles.email, "[email protected]")
monkey_patcher = MonkeyPatcher((user.User, "create", create))
monkey_patcher.patch()
request = self.generate_request(
["/register"],
"""{
"name": "Someone",
"email": "[email protected]"
}""",
)
result = yield self.account.render(request)
self.assertEqual(result.code, http.OK)
self.assertEqual(type(result.subject), dict)
self.assertEqual(result.headers["content-type"], "application/json")
self.assertTrue(result.subject["success"])
示例15: __init__
def __init__(self, pool=None, testing=False):
if pool is not None:
self.pool = pool
self.started = False
self.__testing = testing
if not self.zstorm_configured:
provideUtility(global_zstorm, IZStorm)
zstorm = getUtility(IZStorm)
zstorm.set_default_uri('mamba', config.Database().uri)
SQLite.register()
MySQL.register()
PostgreSQL.register()
# MonkeyPatch Storm
if not self.monkey_patched:
monkey_patcher = MonkeyPatcher(
(properties, 'PropertyColumn', PropertyColumnMambaPatch)
)
monkey_patcher.patch()
self.monkey_patched = True