def test_sealed_exception_has_attribute_name(self): m = mock.Mock() mock.seal(m) with self.assertRaises(AttributeError) as cm: m.SECRETE_name self.assertIn("SECRETE_name", str(cm.exception))
def setUp(self): engine = Mock(revolutions_per_move=2, move_duration=1) engine.go_straight = MagicMock(return_value=True) engine.go_left = MagicMock(return_value=True) engine.go_right = MagicMock(return_value=True) seal(engine.go_straight) self.car = Car(engine)
def test_seal_with_autospec(self): # https://bugs.python.org/issue45156 class Foo: foo = 0 def bar1(self): return 1 def bar2(self): return 2 class Baz: baz = 3 def ban(self): return 4 for spec_set in (True, False): with self.subTest(spec_set=spec_set): foo = mock.create_autospec(Foo, spec_set=spec_set) foo.bar1.return_value = 'a' foo.Baz.ban.return_value = 'b' mock.seal(foo) self.assertIsInstance(foo.foo, mock.NonCallableMagicMock) self.assertIsInstance(foo.bar1, mock.MagicMock) self.assertIsInstance(foo.bar2, mock.MagicMock) self.assertIsInstance(foo.Baz, mock.MagicMock) self.assertIsInstance(foo.Baz.baz, mock.NonCallableMagicMock) self.assertIsInstance(foo.Baz.ban, mock.MagicMock) self.assertEqual(foo.bar1(), 'a') foo.bar1.return_value = 'new_a' self.assertEqual(foo.bar1(), 'new_a') self.assertEqual(foo.Baz.ban(), 'b') foo.Baz.ban.return_value = 'new_b' self.assertEqual(foo.Baz.ban(), 'new_b') with self.assertRaises(TypeError): foo.foo() with self.assertRaises(AttributeError): foo.bar = 1 with self.assertRaises(AttributeError): foo.bar2() foo.bar2.return_value = 'bar2' self.assertEqual(foo.bar2(), 'bar2') with self.assertRaises(AttributeError): foo.missing_attr with self.assertRaises(AttributeError): foo.missing_attr = 1 with self.assertRaises(AttributeError): foo.missing_method() with self.assertRaises(TypeError): foo.Baz.baz() with self.assertRaises(AttributeError): foo.Baz.missing_attr with self.assertRaises(AttributeError): foo.Baz.missing_attr = 1 with self.assertRaises(AttributeError): foo.Baz.missing_method()
def test_existing_attributes_can_be_set_on_seal(self): m = mock.Mock() m.test.test2 = 1 mock.seal(m) m.test.test2 = 2 self.assertEqual(m.test.test2, 2)
def upnp_factory_mock() -> Iterable[Mock]: """Mock the UpnpFactory class to construct DMS-style UPnP devices.""" with patch( "homeassistant.components.dlna_dms.dms.UpnpFactory", autospec=True, spec_set=True, ) as upnp_factory: upnp_device = create_autospec(UpnpDevice, instance=True) upnp_device.name = MOCK_DEVICE_NAME upnp_device.udn = MOCK_DEVICE_UDN upnp_device.device_url = MOCK_DEVICE_LOCATION upnp_device.device_type = MOCK_DEVICE_TYPE upnp_device.available = True upnp_device.parent_device = None upnp_device.root_device = upnp_device upnp_device.all_devices = [upnp_device] upnp_device.services = { "urn:schemas-upnp-org:service:ContentDirectory:1": create_autospec( UpnpService, instance=True, service_type="urn:schemas-upnp-org:service:ContentDirectory:1", service_id="urn:upnp-org:serviceId:ContentDirectory", ), "urn:schemas-upnp-org:service:ConnectionManager:1": create_autospec( UpnpService, instance=True, service_type="urn:schemas-upnp-org:service:ConnectionManager:1", service_id="urn:upnp-org:serviceId:ConnectionManager", ), } seal(upnp_device) upnp_factory_instance = upnp_factory.return_value upnp_factory_instance.async_create_device.return_value = upnp_device yield upnp_factory_instance
def test_main_exception(self, worker_cls, api_cls, room_cls, member_cls): self.maxDiff = None room_api = room_cls() room_api.get.return_value = MagicMock(id="validroomid", title="validtitle") member_api = member_cls() api = api_cls() type(api).rooms = PropertyMock(return_value=room_api) type(api).memberships = PropertyMock(return_value=member_api) seal(api) api_cls.return_value = api worker = worker_cls.return_value worker.get_param.side_effect = [None] main() self.assertListEqual(member_api.method_calls, []) self.assertListEqual(room_api.method_calls, []) self.assertListEqual(worker_cls.method_calls, [ call().get_param('config.webex_bot_token', default=None), call().error(message='Missing parameter: "config.webex_bot_token"', ensure_ascii=False) ])
def test_new_attributes_cannot_be_set_on_child_of_seal(self): m = mock.Mock() m.test.test2 = 1 mock.seal(m) with self.assertRaises(AttributeError): m.test.test3 = 1
def test_cfs_check_tlm_packet_errors(cfs, utils): Global.current_verification_stage = CtfVerificationStage.first_ver payload = MagicMock() payload.__str__.return_value = 'mock payload' payload.myint = 42 seal(payload) # no args assert cfs.check_tlm_packet(payload, []) # no value assert not cfs.check_tlm_packet(payload, [{ 'variable': 'myint', 'compare': '==' }]) assert utils.has_log_level('ERROR') utils.clear_log() # no variable assert not cfs.check_tlm_packet(payload, [{'compare': '==', 'value': 42}]) assert utils.has_log_level('ERROR') utils.clear_log() # invalid variable assert not cfs.check_tlm_packet(payload, [{ 'variable': 'int', 'compare': '==', 'value': 42 }]) assert utils.has_log_level('ERROR') utils.clear_log()
def test_existing_attributes_allowed_after_seal(self): m = mock.Mock() m.test.return_value = 3 mock.seal(m) self.assertEqual(m.test(), 3)
def MockClient(): #No-op, seal doesn't exist in Python 3.6 if sys.version_info >= (3, 7, 0): from unittest.mock import seal else: seal = lambda x: x notionClient = Mock() notionClient.return_value = notionClient getBlock = Mock(spec=PageBlock) class MockNodeList(list): def add_new(self, t, title=None): m = Mock(spec=t) def remove(): self.remove(m) return None m.remove = Mock(return_value=None, side_effect=remove) m.title = title seal(m) self.append(m) return m getBlock.children = MockNodeList() getBlock.title = Mock(return_value="") notionClient.get_block = Mock(return_value=getBlock) seal(getBlock) seal(notionClient) return notionClient
def test_call_chain_is_maintained(self): m = mock.Mock() m.test1().test2.test3().test4 mock.seal(m) with self.assertRaises(AttributeError) as cm: m.test1().test2.test3().test4() self.assertIn("mock.test1().test2.test3().test4", str(cm.exception))
def test_attribute_chain_is_maintained(self): m = mock.Mock(name="mock_name") m.test1.test2.test3.test4 mock.seal(m) with self.assertRaises(AttributeError) as cm: m.test1.test2.test3.test4.boom self.assertIn("mock_name.test1.test2.test3.test4.boom", str(cm.exception))
def test_new_attributes_cannot_be_accessed_on_seal(self): m = mock.Mock() mock.seal(m) with self.assertRaises(AttributeError): m.test with self.assertRaises(AttributeError): m()
def generate_Class1_pb(): obj = Mock() obj.value1 = random.choice(string.ascii_lowercase) obj.value2 = random.randint(0, 1000) obj.value3 = [random.choice(string.ascii_lowercase) for _ in range(5)] obj.value4 = random.randint(1, 10000) / 10.0 seal(obj) return obj
def test_integration_with_spec_method_definition(self): """You need to define the methods, even if they are in the spec""" m = mock.Mock(SampleObject) m.method_sample1.return_value = 1 mock.seal(m) self.assertEqual(m.method_sample1(), 1) with self.assertRaises(AttributeError): m.method_sample2()
def test_seals_dont_recurse_on_manual_attributes(self): m = mock.Mock(name="root_mock") m.test1.test2 = mock.Mock(name="not_sealed") m.test1.test2.test3 = 4 mock.seal(m) self.assertEqual(m.test1.test2.test3, 4) m.test1.test2.test4 # Does not raise m.test1.test2.test4 = 1 # Does not raise
def test_with_autospec(self): with mock.patch('src.myapp.dummy_class.DummyClass', autospec=True) as a_mock: a_mock.bar = Mock() # allowed with spec before sealing mock.seal(a_mock) # once the mock is sealed, # an addition of attributes is not allowed with pytest.raises(AttributeError): # AttributeError: Cannot set A.another_attribute a_mock.another_attribute = Mock()
def add_new(self, t, title=None): m = Mock(spec=t) def remove(): self.remove(m) return None m.remove = Mock(return_value=None, side_effect=remove) m.title = title seal(m) self.append(m) return m
def test_seals_recurse_on_added_attributes(self): m = mock.Mock() m.test1.test2().test3 = 4 mock.seal(m) self.assertEqual(m.test1.test2().test3, 4) with self.assertRaises(AttributeError): m.test1.test2().test4 with self.assertRaises(AttributeError): m.test1.test3
def test_integration_with_spec_att_definition(self): """You are not restricted when using mock with spec""" m = mock.Mock(SampleObject) m.attr_sample1 = 1 m.attr_sample3 = 3 mock.seal(m) self.assertEqual(m.attr_sample1, 1) self.assertEqual(m.attr_sample3, 3) with self.assertRaises(AttributeError): m.attr_sample2
def test_seals_recurse_on_magic_methods(self): m = mock.MagicMock() m.test1.test2["a"].test3 = 4 m.test1.test3[2:5].test3 = 4 mock.seal(m) self.assertEqual(m.test1.test2["a"].test3, 4) self.assertEqual(m.test1.test2[2:5].test3, 4) with self.assertRaises(AttributeError): m.test1.test2["a"].test4 with self.assertRaises(AttributeError): m.test1.test3[2:5].test4
def MockBlock(title='', icon=None, createdTime=defaultBlockTimeNotion, lastEditedTime=None, spec=PageBlock): mockBlock = Mock(spec=spec) mockBlock._get_record_data = Mock( return_value={ "created_time": createdTime, "last_edited_time": lastEditedTime or createdTime }) mockBlock.icon = icon mockBlock.title = title seal(mockBlock) return mockBlock
def domain_data_mock(hass: HomeAssistant) -> Iterable[Mock]: """Mock the global data used by this component. This includes network clients and library object factories. Mocking it prevents network use. """ domain_data = create_autospec(DlnaDmrData, instance=True) domain_data.upnp_factory = create_autospec(UpnpFactory, spec_set=True, instance=True) upnp_device = create_autospec(UpnpDevice, instance=True) upnp_device.name = MOCK_DEVICE_NAME upnp_device.udn = MOCK_DEVICE_UDN upnp_device.device_url = MOCK_DEVICE_LOCATION upnp_device.device_type = "urn:schemas-upnp-org:device:MediaRenderer:1" upnp_device.available = True upnp_device.parent_device = None upnp_device.root_device = upnp_device upnp_device.all_devices = [upnp_device] upnp_device.services = { "urn:schemas-upnp-org:service:AVTransport:1": create_autospec( UpnpService, instance=True, service_type="urn:schemas-upnp-org:service:AVTransport:1", service_id="urn:upnp-org:serviceId:AVTransport", ), "urn:schemas-upnp-org:service:ConnectionManager:1": create_autospec( UpnpService, instance=True, service_type="urn:schemas-upnp-org:service:ConnectionManager:1", service_id="urn:upnp-org:serviceId:ConnectionManager", ), "urn:schemas-upnp-org:service:RenderingControl:1": create_autospec( UpnpService, instance=True, service_type="urn:schemas-upnp-org:service:RenderingControl:1", service_id="urn:upnp-org:serviceId:RenderingControl", ), } seal(upnp_device) domain_data.upnp_factory.async_create_device.return_value = upnp_device with patch.dict(hass.data, {DLNA_DOMAIN: domain_data}): yield domain_data
async def test_app_with_lifespan_uses_callbacks(): startup = AsyncMock(return_value=None) shutdown = AsyncMock(return_value=None) seal(startup), seal(shutdown) async with TestClient( AppWithLifespan( app=AppBasic(MgFixed(RsText("Hello there!"))), startup=startup, shutdown=shutdown, ), ) as client: startup.assert_awaited_once() shutdown.assert_not_awaited() resp = await client.get("/") assert resp.status_code == 200 assert resp.content == b"Hello there!" shutdown.assert_awaited_once()
def _mock_response(resp: JsonDict): body = json.dumps(resp).encode("utf-8") def deliver_body(p: Protocol): p.dataReceived(body) p.connectionLost(Failure(twisted.web.client.ResponseDone())) response = mock.Mock( code=200, phrase=b"OK", headers=twisted.web.client.Headers( {"content-Type": ["application/json"]}), length=len(body), deliverBody=deliver_body, ) mock.seal(response) return response
def test_GIVEN_one_old_one_new_THEN_prune_old(self, old, new): from cellxgene_gateway.prune_process_cache import PruneProcessCache cache = BackendCache() old.timestamp = -100 old.foo = 12 old.pid = 1 old.key = key old.terminate.return_value = None seal(old) new.key = key cache.entry_list.append(old) new.timestamp = -5 seal(new) cache.entry_list.append(new) self.assertEqual(len(cache.entry_list), 2) ppc = PruneProcessCache(cache) ppc.prune() self.assertEqual(len(cache.entry_list), 1) self.assertEqual(cache.entry_list[0], new) self.assertEqual(cache.entry_list[0], new) self.assertTrue(old.terminate.called)
#!/usr/bin/env python3 from unittest import mock m = mock.Mock() m.a = 1 mock.seal(m) m.a = 2 # OK m.b = 2 # AttributeError: Cannot set mock.b
def test_call_on_defined_sealed_mock_succeeds(self): m = mock.Mock(return_value=5) mock.seal(m) self.assertEqual(m(), 5)
def test_call_on_sealed_mock_fails(self): m = mock.Mock() mock.seal(m) with self.assertRaises(AttributeError): m()
def test_initialized_attributes_allowed_after_seal(self): m = mock.Mock(test_value=1) mock.seal(m) self.assertEqual(m.test_value, 1)