1# mypy: allow-untyped-defs 2_magic_methods = [ 3 "__subclasscheck__", 4 "__hex__", 5 "__rmul__", 6 "__float__", 7 "__idiv__", 8 "__setattr__", 9 "__div__", 10 "__invert__", 11 "__nonzero__", 12 "__rshift__", 13 "__eq__", 14 "__pos__", 15 "__round__", 16 "__rand__", 17 "__or__", 18 "__complex__", 19 "__divmod__", 20 "__len__", 21 "__reversed__", 22 "__copy__", 23 "__reduce__", 24 "__deepcopy__", 25 "__rdivmod__", 26 "__rrshift__", 27 "__ifloordiv__", 28 "__hash__", 29 "__iand__", 30 "__xor__", 31 "__isub__", 32 "__oct__", 33 "__ceil__", 34 "__imod__", 35 "__add__", 36 "__truediv__", 37 "__unicode__", 38 "__le__", 39 "__delitem__", 40 "__sizeof__", 41 "__sub__", 42 "__ne__", 43 "__pow__", 44 "__bytes__", 45 "__mul__", 46 "__itruediv__", 47 "__bool__", 48 "__iter__", 49 "__abs__", 50 "__gt__", 51 "__iadd__", 52 "__enter__", 53 "__floordiv__", 54 "__call__", 55 "__neg__", 56 "__and__", 57 "__ixor__", 58 "__getitem__", 59 "__exit__", 60 "__cmp__", 61 "__getstate__", 62 "__index__", 63 "__contains__", 64 "__floor__", 65 "__lt__", 66 "__getattr__", 67 "__mod__", 68 "__trunc__", 69 "__delattr__", 70 "__instancecheck__", 71 "__setitem__", 72 "__ipow__", 73 "__ilshift__", 74 "__long__", 75 "__irshift__", 76 "__imul__", 77 "__lshift__", 78 "__dir__", 79 "__ge__", 80 "__int__", 81 "__ior__", 82] 83 84 85class MockedObject: 86 _name: str 87 88 def __new__(cls, *args, **kwargs): 89 # _suppress_err is set by us in the mocked module impl, so that we can 90 # construct instances of MockedObject to hand out to people looking up 91 # module attributes. 92 93 # Any other attempt to construct a MockedObject instance (say, in the 94 # unpickling process) should give an error. 95 if not kwargs.get("_suppress_err"): 96 raise NotImplementedError( 97 f"Object '{cls._name}' was mocked out during packaging " 98 f"but it is being used in '__new__'. If this error is " 99 "happening during 'load_pickle', please ensure that your " 100 "pickled object doesn't contain any mocked objects." 101 ) 102 # Otherwise, this is just a regular object creation 103 # (e.g. `x = MockedObject("foo")`), so pass it through normally. 104 return super().__new__(cls) 105 106 def __init__(self, name: str, _suppress_err: bool): 107 self.__dict__["_name"] = name 108 109 def __repr__(self): 110 return f"MockedObject({self._name})" 111 112 113def install_method(method_name): 114 def _not_implemented(self, *args, **kwargs): 115 raise NotImplementedError( 116 f"Object '{self._name}' was mocked out during packaging but it is being used in {method_name}" 117 ) 118 119 setattr(MockedObject, method_name, _not_implemented) 120 121 122for method_name in _magic_methods: 123 install_method(method_name) 124