A unittest for the metaclass.

This commit is contained in:
Itamar Turner-Trauring 2022-07-29 10:42:56 -04:00
parent 533d2a7ac9
commit d4c73f19fe
2 changed files with 49 additions and 4 deletions

View File

@ -31,13 +31,15 @@ from .storage.server import StorageServer
class _PretendToBeNegotiation(type): class _PretendToBeNegotiation(type):
""" """
Metaclass that allows ``_FoolscapOrHttps`` to pretend to be a ``Negotiation`` Metaclass that allows ``_FoolscapOrHttps`` to pretend to be a
instance, since Foolscap has some ``assert isinstance(protocol, ``Negotiation`` instance, since Foolscap does some checks like
Negotiation`` checks. ``assert isinstance(protocol, tub.negotiationClass)`` in its internals,
and sometimes that ``protocol`` is a ``_FoolscapOrHttps`` instance, but
sometimes it's a ``Negotiation`` instance.
""" """
def __instancecheck__(self, instance): def __instancecheck__(self, instance):
return (instance.__class__ == self) or isinstance(instance, Negotiation) return issubclass(instance.__class__, self) or isinstance(instance, Negotiation)
class _FoolscapOrHttps(Protocol, metaclass=_PretendToBeNegotiation): class _FoolscapOrHttps(Protocol, metaclass=_PretendToBeNegotiation):

View File

@ -0,0 +1,43 @@
"""
Unit tests for ``allmydata.protocol_switch``.
By its nature, most of the testing needs to be end-to-end; essentially any test
that uses real Foolscap (``test_system.py``, integration tests) ensures
Foolscap still works. ``test_istorageserver.py`` tests the HTTP support.
"""
from foolscap.negotiate import Negotiation
from .common import TestCase
from ..protocol_switch import _PretendToBeNegotiation
class UtilityTests(TestCase):
"""Tests for utilities in the protocol switch code."""
def test_metaclass(self):
"""
A class that has the ``_PretendToBeNegotiation`` metaclass will support
``isinstance()``'s normal semantics on its own instances, but will also
indicate that ``Negotiation`` instances are its instances.
"""
class Parent(metaclass=_PretendToBeNegotiation):
pass
class Child(Parent):
pass
class Other:
pass
p = Parent()
self.assertIsInstance(p, Parent)
self.assertIsInstance(Negotiation(), Parent)
self.assertNotIsInstance(Other(), Parent)
c = Child()
self.assertIsInstance(c, Child)
self.assertIsInstance(c, Parent)
self.assertIsInstance(Negotiation(), Child)
self.assertNotIsInstance(Other(), Child)