当前位置: 首页>>代码示例>>Python>>正文


Python monkey.MonkeyPatcher类代码示例

本文整理汇总了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)
开发者ID:DamnWidget,项目名称:BlackMamba,代码行数:25,代码来源:test_controller_account.py

示例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
开发者ID:aroshni,项目名称:mamba,代码行数:27,代码来源:postgres.py

示例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)
开发者ID:wangdayoux,项目名称:OpenSignals,代码行数:10,代码来源:test_monkey.py

示例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()
开发者ID:aburan28,项目名称:DHTBot,代码行数:28,代码来源:test_datastore.py

示例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)
开发者ID:BillAndersan,项目名称:twisted,代码行数:11,代码来源:test_monkey.py

示例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
开发者ID:ClusterHQ,项目名称:flocker,代码行数:50,代码来源:test_cinder.py

示例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)
开发者ID:nicholasamorim,项目名称:mamba,代码行数:48,代码来源:postgres.py

示例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
开发者ID:edisonlz,项目名称:mdht,代码行数:7,代码来源:test_krpc_iterator.py

示例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
开发者ID:DamnWidget,项目名称:mamba,代码行数:16,代码来源:app.py

示例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,
     )
开发者ID:332054781,项目名称:flocker,代码行数:26,代码来源:test_diffing.py

示例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)
开发者ID:Bull-Labs,项目名称:CloudMalwareAlarm,代码行数:19,代码来源:test_cli_backup.py

示例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'])
开发者ID:DamnWidget,项目名称:BlackMamba,代码行数:20,代码来源:test_controller_account.py

示例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])
开发者ID:FiloSottile,项目名称:tahoe-lafs,代码行数:21,代码来源:test_import.py

示例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"])
开发者ID:PyMamba,项目名称:BlackMamba,代码行数:22,代码来源:test_controller_account.py

示例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
开发者ID:aroshni,项目名称:mamba,代码行数:23,代码来源:database.py


注:本文中的twisted.python.monkey.MonkeyPatcher类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。