def test_returns_none_when_matches(self): mock = Mock() mock(1, 2, frob=5, nob=6) matcher = MockCalledWith(1, 2, frob=5, nob=6) result = matcher.match(mock) self.assertIsNone(result)
def test__power_on(self): driver = OpenBMCPowerDriver() system_id = factory.make_name('system_id') context = make_context() url = driver.get_uri(context, HOST_STATE + 'RequestedHostTransition') mock_file_body_producer = self.patch( openbmc_module, 'FileBodyProducer') dataon = FileBodyProducer(BytesIO(json.dumps( HOST_ON).encode('utf-8'))) mock_openbmc_request = self.patch(driver, 'openbmc_request') mock_openbmc_request.return_value = dataon mock_file_body_producer.return_value = dataon mock_power_query = self.patch(driver, 'power_query') mock_power_query.return_value = 'on' mock_command = self.patch(driver, 'command') mock_command.return_value = SAMPLE_JSON_HOSTOFF mock_set_pxe_boot = self.patch(driver, 'set_pxe_boot') yield driver.power_on(system_id, context) self.assertThat(mock_power_query, MockCalledOnceWith( system_id, context)) self.assertThat(mock_set_pxe_boot, MockCalledWith( context)) self.assertThat(mock_command, MockCalledWith( context, b'PUT', url, dataon))
def test_returns_mismatch_when_does_not_match(self): mock = Mock() mock(1, 2, a=5) matcher = MockCalledWith(9, 2, a=5) result = matcher.match(mock) self.assertMismatch(result, "Expected call:")
def test_signal_formats_params_with_script_version_id(self): mock_encode_multipart_data = self.patch(maas_api_helper, 'encode_multipart_data') mock_encode_multipart_data.return_value = None, None mock_geturl = self.patch(maas_api_helper, 'geturl') mm = MagicMock() mm.status = 200 mm.read.return_value = b'OK' mock_geturl.return_value = mm status = factory.make_name('status') script_version_id = random.randint(1, 1000) # None used for url and creds as we're not actually sending data. maas_api_helper.signal(None, None, status, script_version_id=script_version_id) self.assertThat( mock_encode_multipart_data, MockCalledWith( { b'op': b'signal', b'status': status.encode('utf-8'), b'script_version_id': str(script_version_id).encode('utf-8'), }, {})) self.assertThat(mock_geturl, MockCalledOnce())
def test_signal_formats_params_with_exit_status(self): mock_encode_multipart_data = self.patch( maas_api_helper, "encode_multipart_data" ) mock_encode_multipart_data.return_value = None, None mock_geturl = self.patch(maas_api_helper, "geturl") mm = MagicMock() mm.status = 200 mm.read.return_value = b"OK" mock_geturl.return_value = mm status = factory.make_name("status") exit_status = random.randint(0, 255) # None used for url and creds as we're not actually sending data. maas_api_helper.signal(None, None, status, exit_status=exit_status) self.assertThat( mock_encode_multipart_data, MockCalledWith( { b"op": b"signal", b"status": status.encode("utf-8"), b"exit_status": str(exit_status).encode("utf-8"), }, files=None, ), ) self.assertThat(mock_geturl, MockCalledOnce())
def test_calls_update_services_in_database_thread(self): system_id = factory.make_name("system_id") services = [ { "name": factory.make_name("service"), "status": factory.make_name("status"), "status_info": factory.make_name("status_info"), } ] mock_deferToDatabase = self.patch(regionservice, "deferToDatabase") mock_deferToDatabase.return_value = succeed({}) yield eventloop.start() try: yield call_responder( Region(), UpdateServices, {"system_id": system_id, "services": services}, ) finally: yield eventloop.reset() self.assertThat( mock_deferToDatabase, MockCalledWith(update_services, system_id, services), )
def test_calls_download_boot_resources(self): self.patch(download_resources, "datetime", MockDateTime) storage_path = self.make_dir() snapshot_path = download_resources.compose_snapshot_path(storage_path) cache_path = os.path.join(storage_path, "cache") file_store = FileStore(cache_path) source = { "url": "http://example.com", "keyring": self.make_file("keyring"), } product_mapping = ProductMapping() fake = self.patch(download_resources, "download_boot_resources") download_resources.download_all_boot_resources( sources=[source], storage_path=storage_path, product_mapping=product_mapping, store=file_store, ) self.assertThat( fake, MockCalledWith( source["url"], file_store, snapshot_path, product_mapping, keyring_file=source["keyring"], ), )
def test_query_all_nodes_skips_nodes_in_action_registry(self): nodes = self.make_nodes() # First node is in the registry. power.power_action_registry[nodes[0]["system_id"]] = sentinel.action # Report back power state of nodes' not in registry. power_states = [node["power_state"] for node in nodes[1:]] get_power_state = self.patch(power, "get_power_state") get_power_state.side_effect = map(succeed, power_states) suppress_reporting(self) yield power.query_all_nodes(nodes) self.assertThat( get_power_state, MockCallsMatch(*(call( node["system_id"], node["hostname"], node["power_type"], node["context"], clock=reactor, ) for node in nodes[1:])), ) self.assertThat( get_power_state, Not( MockCalledWith( nodes[0]["system_id"], nodes[0]["hostname"], nodes[0]["power_type"], nodes[0]["context"], clock=reactor, )), )
def test__calls_power_driver_cycle_for_power_driver(self): system_id = factory.make_name('system_id') hostname = factory.make_name('hostname') power_driver = random.choice( [driver for _, driver in PowerDriverRegistry if driver.queryable]) power_change = 'cycle' context = { factory.make_name('context-key'): factory.make_name('context-val') } self.patch(power, 'is_driver_available').return_value = True get_item = self.patch(PowerDriverRegistry, 'get_item') perform_power_driver_query = self.patch(power, 'perform_power_driver_query') perform_power_driver_query.return_value = succeed('on') self.patch(power, 'power_change_success') yield self.patch_rpc_methods() result = yield power.change_power_state(system_id, hostname, power_driver.name, power_change, context) self.expectThat(get_item, MockCalledWith(power_driver.name)) self.expectThat( perform_power_driver_query, MockCalledOnceWith(system_id, hostname, power_driver.name, context)) self.expectThat(power.power_change_success, MockCalledOnceWith(system_id, hostname, 'on')) self.expectThat(result, Equals('on'))
def test_writes_source_keyrings(self): # Stop import_images() from actually doing anything. self.patch(boot_resources, "maaslog") self.patch(boot_resources, "try_send_rack_event") self.patch(boot_resources, "call_and_check") self.patch(boot_resources, "download_all_boot_resources") self.patch(boot_resources, "download_all_image_descriptions") self.patch(boot_resources, "install_boot_loaders") self.patch(boot_resources, "update_current_symlink") self.patch(boot_resources, "write_snapshot_metadata") self.patch(boot_resources, "write_targets_conf") self.patch(boot_resources, "update_targets_conf") fake_write_all_keyrings = self.patch(boot_resources, "write_all_keyrings") sources = ([{ "keyring_data": self.getUniqueString(), "url": factory.make_name("something"), "selections": [{ "os": factory.make_name("os"), "release": factory.make_name("release"), "arches": [factory.make_name("arch")], "subarches": [factory.make_name("subarch")], "labels": [factory.make_name("label")], }], }], ) boot_resources.import_images(sources) self.assertThat(fake_write_all_keyrings, MockCalledWith(mock.ANY, sources))
def test_sets_and_resets_egid(self): original_egid = os.getegid() example_egid = original_egid + random.randrange(500, 1000) self.useFixture(EnvironmentVariable("SUDO_GID", str(example_egid))) with utils.sudo_gid(): self.assertThat(utils.setegid, MockCalledOnceWith(example_egid)) self.assertThat(utils.setegid, MockCalledWith(original_egid))
def test_arranges_for_update_on_BootSource_create(self): post_commit_do = self.patch(signals.bootsources, "post_commit_do") factory.make_BootSource(keyring_data=factory.make_bytes()) factory.make_BootSource(keyring_data=factory.make_bytes()) self.assertThat( post_commit_do, MockCalledWith(reactor.callLater, 0, cache_boot_sources))
def test_return_none_when_unqueryable(self): system_id = factory.make_name("system_id") hostname = factory.make_name("hostname") power_driver = random.choice( [ driver for _, driver in PowerDriverRegistry if not driver.queryable ] ) power_change = "on" context = { factory.make_name("context-key"): factory.make_name("context-val") } self.patch(power, "is_driver_available").return_value = True get_item = self.patch(PowerDriverRegistry, "get_item") get_item.return_value = MagicMock() get_item.return_value.queryable = False perform_power_driver_query = self.patch( power, "perform_power_driver_query" ) perform_power_driver_query.return_value = succeed(power_change) self.patch(power, "power_change_success") yield self.patch_rpc_methods() result = yield power.change_power_state( system_id, hostname, power_driver.name, power_change, context ) self.expectThat(get_item, MockCalledWith(power_driver.name)) self.expectThat(perform_power_driver_query, MockNotCalled()) self.expectThat(power.power_change_success, MockNotCalled()) self.expectThat(result, Equals(None))
def test_signal_formats_params_with_script_version_id(self): mock_encode_multipart_data = self.patch(maas_api_helper, "encode_multipart_data") mock_encode_multipart_data.return_value = None, None mock_geturl = self.patch(maas_api_helper, "geturl") mm = MagicMock() mm.status = 200 mm.read.return_value = b"OK" mock_geturl.return_value = mm status = factory.make_name("status") script_version_id = random.randint(1, 1000) # None used for url and creds as we're not actually sending data. maas_api_helper.signal(None, None, status, script_version_id=script_version_id) self.assertThat( mock_encode_multipart_data, MockCalledWith( { b"op": b"signal", b"status": status.encode("utf-8"), b"script_version_id": str(script_version_id).encode("utf-8"), }, {}, ), ) self.assertThat(mock_geturl, MockCalledOnce())
def test_writes_source_keyrings(self): # Stop import_images() from actually doing anything. self.patch(boot_resources, 'maaslog') self.patch(boot_resources, 'try_send_rack_event') self.patch(boot_resources, 'call_and_check') self.patch(boot_resources, 'download_all_boot_resources') self.patch(boot_resources, 'download_all_image_descriptions') self.patch(boot_resources, 'install_boot_loaders') self.patch(boot_resources, 'update_current_symlink') self.patch(boot_resources, 'write_snapshot_metadata') self.patch(boot_resources, 'write_targets_conf') self.patch(boot_resources, 'update_targets_conf') fake_write_all_keyrings = self.patch(boot_resources, 'write_all_keyrings') sources = [ { 'keyring_data': self.getUniqueString(), 'url': factory.make_name("something"), 'selections': [ { 'os': factory.make_name("os"), 'release': factory.make_name("release"), 'arches': [factory.make_name("arch")], 'subarches': [factory.make_name("subarch")], 'labels': [factory.make_name("label")], }, ], }, ], boot_resources.import_images(sources) self.assertThat(fake_write_all_keyrings, MockCalledWith(mock.ANY, sources))
def test_calls_save_on_related_filesystem_groups(self): mock_filter_by_block_device = self.patch(FilesystemGroup.objects, "filter_by_block_device") mock_filesystem_group = MagicMock() mock_filter_by_block_device.return_value = [mock_filesystem_group] self.factory() self.assertThat(mock_filesystem_group.save, MockCalledWith())
def test_signal_formats_files(self): mock_encode_multipart_data = self.patch(maas_api_helper, "encode_multipart_data") mock_encode_multipart_data.return_value = None, None mock_geturl = self.patch(maas_api_helper, "geturl") mm = MagicMock() mm.status = 200 mm.read.return_value = b"OK" mock_geturl.return_value = mm status = factory.make_name("status") files = {factory.make_name(): factory.make_bytes()} # None used for url and creds as we're not actually sending data. maas_api_helper.signal(None, None, status, files=files) self.assertThat( mock_encode_multipart_data, MockCalledWith( { b"op": b"signal", b"status": status.encode("utf-8") }, files), ) self.assertThat(mock_geturl, MockCalledOnce())
def test_calls_power_driver_cycle_for_power_driver(self): system_id = factory.make_name("system_id") hostname = factory.make_name("hostname") power_driver = random.choice( [driver for _, driver in PowerDriverRegistry if driver.queryable] ) power_change = "cycle" context = { factory.make_name("context-key"): factory.make_name("context-val") } self.patch(power, "is_driver_available").return_value = True get_item = self.patch(PowerDriverRegistry, "get_item") perform_power_driver_query = self.patch( power, "perform_power_driver_query" ) perform_power_driver_query.return_value = succeed("on") self.patch(power, "power_change_success") yield self.patch_rpc_methods() result = yield power.change_power_state( system_id, hostname, power_driver.name, power_change, context ) self.expectThat(get_item, MockCalledWith(power_driver.name)) self.expectThat( perform_power_driver_query, MockCalledOnceWith( system_id, hostname, power_driver.name, context ), ) self.expectThat( power.power_change_success, MockCalledOnceWith(system_id, hostname, "on"), ) self.expectThat(result, Equals("on"))
def test_sets_and_resets_egid_on_crash(self): original_egid = os.getegid() example_egid = original_egid + random.randrange(500, 1000) self.useFixture(EnvironmentVariable("SUDO_GID", str(example_egid))) with ExpectedException(ZeroDivisionError): with utils.sudo_gid(): 0 / 0 # A very realistic example. self.assertThat(utils.setegid, MockCalledWith(original_egid))
def test_onNotify_calls_handler_class_on_listen(self): user = yield deferToDatabase(self.make_user) protocol, factory = self.make_protocol_with_factory(user=user) mock_class = MagicMock() mock_class.return_value.on_listen.return_value = None yield factory.onNotify( mock_class, sentinel.channel, sentinel.action, sentinel.obj_id) self.assertThat( mock_class.return_value.on_listen, MockCalledWith(sentinel.channel, sentinel.action, sentinel.obj_id))
def test_onNotify_calls_sendNotify_on_protocol(self): user = yield deferToDatabase(self.make_user) protocol, factory = self.make_protocol_with_factory(user=user) name = maas_factory.make_name("name") action = maas_factory.make_name("action") data = maas_factory.make_name("data") mock_class = MagicMock() mock_class.return_value.on_listen.return_value = (name, action, data) mock_sendNotify = self.patch(protocol, "sendNotify") yield factory.onNotify(mock_class, sentinel.channel, action, sentinel.obj_id) self.assertThat(mock_sendNotify, MockCalledWith(name, action, data))
def test_tryConnection_will_retry_in_3_seconds_if_autoReconnect_set(self): listener = PostgresListenerService() listener.autoReconnect = True startConnection = self.patch(listener, "startConnection") startConnection.side_effect = factory.make_exception() deferLater = self.patch(listener_module, "deferLater") deferLater.return_value = sentinel.retry result = yield listener.tryConnection() self.assertThat(result, Is(sentinel.retry)) self.assertThat(deferLater, MockCalledWith(reactor, 3, ANY))
def test__power_on(self): driver = OpenBMCPowerDriver() system_id = factory.make_name("system_id") context = make_context() url = driver.get_uri(context, HOST_STATE + "RequestedHostTransition") mock_file_body_producer = self.patch(openbmc_module, "FileBodyProducer") dataon = FileBodyProducer(BytesIO(json.dumps(HOST_ON).encode("utf-8"))) mock_openbmc_request = self.patch(driver, "openbmc_request") mock_openbmc_request.return_value = dataon mock_file_body_producer.return_value = dataon mock_power_query = self.patch(driver, "power_query") mock_power_query.return_value = "on" mock_command = self.patch(driver, "command") mock_command.return_value = SAMPLE_JSON_HOSTOFF mock_set_pxe_boot = self.patch(driver, "set_pxe_boot") yield driver.power_on(system_id, context) self.assertThat(mock_power_query, MockCalledOnceWith(system_id, context)) self.assertThat(mock_set_pxe_boot, MockCalledWith(context)) self.assertThat(mock_command, MockCalledWith(context, b"PUT", url, dataon))
def test_signal_formats_basic_params(self): mock_encode_multipart_data = self.patch( maas_api_helper, 'encode_multipart_data') mock_encode_multipart_data.return_value = None, None mock_geturl = self.patch(maas_api_helper, 'geturl') mock_geturl.return_value = b'OK' status = factory.make_name('status') # None used for url and creds as we're not actually sending data. maas_api_helper.signal(None, None, status) self.assertThat( mock_encode_multipart_data, MockCalledWith({ b'op': b'signal', b'status': status.encode('utf-8'), }, {})) self.assertThat(mock_geturl, MockCalledOnce())
def test_ignores_existing_keyrings(self): self.patch(keyrings, 'write_keyring') fake_maaslog = self.patch(keyrings, 'maaslog') source = { 'url': self.getUniqueString(), 'keyring': self.getUniqueString(), 'keyring_data': self.getUniqueString(), } keyring_path = self.make_dir() [returned_source] = keyrings.write_all_keyrings(keyring_path, [source]) expected_keyring = os.path.join( keyring_path, keyrings.calculate_keyring_name(source['url'])) self.assertEqual(expected_keyring, returned_source.get('keyring')) self.assertThat( fake_maaslog.warning, MockCalledWith( "Both a keyring file and keyring data were specified; " "ignoring the keyring file."))
def test_signal_formats_files(self): mock_encode_multipart_data = self.patch(maas_api_helper, 'encode_multipart_data') mock_encode_multipart_data.return_value = None, None mock_geturl = self.patch(maas_api_helper, 'geturl') mm = MagicMock() mm.status = 200 mm.read.return_value = b'OK' mock_geturl.return_value = mm status = factory.make_name('status') files = {factory.make_name(): factory.make_bytes()} # None used for url and creds as we're not actually sending data. maas_api_helper.signal(None, None, status, files=files) self.assertThat( mock_encode_multipart_data, MockCalledWith( { b'op': b'signal', b'status': status.encode('utf-8'), }, files)) self.assertThat(mock_geturl, MockCalledOnce())
def test_calls_download_boot_resources(self): self.patch(download_resources, 'datetime', MockDateTime) storage_path = self.make_dir() snapshot_path = download_resources.compose_snapshot_path(storage_path) cache_path = os.path.join(storage_path, 'cache') file_store = FileStore(cache_path) source = { 'url': 'http://example.com', 'keyring': self.make_file("keyring"), } product_mapping = ProductMapping() fake = self.patch(download_resources, 'download_boot_resources') download_resources.download_all_boot_resources( sources=[source], storage_path=storage_path, product_mapping=product_mapping, store=file_store) self.assertThat( fake, MockCalledWith(source['url'], file_store, snapshot_path, product_mapping, keyring_file=source['keyring']))
def test_probe_seamicro15k_and_enlist_v09(self): self.configure_api_v09_login() user = factory.make_name("user") ip = factory.make_ipv4_address() username = factory.make_name("username") password = factory.make_name("password") system_id = factory.make_name("system_id") domain = factory.make_name("domain") result = { 0: { "serverId": "0/0", "serverNIC": "0", "serverMacAddr": factory.make_mac_address(), }, 1: { "serverId": "1/0", "serverNIC": "0", "serverMacAddr": factory.make_mac_address(), }, 2: { "serverId": "2/0", "serverNIC": "0", "serverMacAddr": factory.make_mac_address(), }, 3: { "serverId": "3/1", "serverNIC": "1", "serverMacAddr": factory.make_mac_address(), }, } self.patch(SeaMicroAPIV09, "get", Mock(return_value=result)) mock_create_node = self.patch(seamicro, "create_node") mock_create_node.side_effect = asynchronous(lambda *_, **__: system_id) mock_commission_node = self.patch(seamicro, "commission_node") yield deferToThread( probe_seamicro15k_and_enlist, user, ip, username, password, power_control="restapi", accept_all=True, domain=domain, ) self.assertEqual(3, mock_create_node.call_count) last = result[2] power_params = { "power_control": "restapi", "system_id": last["serverId"].split("/")[0], "power_address": ip, "power_pass": password, "power_user": username, } self.expectThat( mock_create_node, MockCalledWith( last["serverMacAddr"], "amd64", "sm15k", power_params, domain=domain, ), ) self.expectThat(mock_commission_node, MockCalledWith(system_id, user))
def test_str(self): matcher = MockCalledWith(1, a=2) self.assertEqual("MockCalledWith(args=(1,), kwargs={'a': 2})", matcher.__str__())
def test_probe_seamicro15k_and_enlist_v2(self): user = factory.make_name("user") ip = factory.make_ipv4_address() username = factory.make_name("username") password = factory.make_name("password") system_id = factory.make_name("system_id") fake_server_0 = FakeServer("0/0") fake_server_0.add_fake_nic("0") fake_server_0.add_fake_nic("1") fake_server_1 = FakeServer("1/0") fake_server_1.add_fake_nic("0") fake_server_1.add_fake_nic("1") fake_client = FakeSeaMicroClient() fake_client.servers = FakeSeaMicroServerManager() fake_client.servers.servers.append(fake_server_0) fake_client.servers.servers.append(fake_server_1) mock_get_api = self.patch(seamicro, "get_seamicro15k_api") mock_get_api.return_value = fake_client mock_create_node = self.patch(seamicro, "create_node") mock_create_node.side_effect = asynchronous(lambda *_, **__: system_id) mock_commission_node = self.patch(seamicro, "commission_node") yield deferToThread( probe_seamicro15k_and_enlist, user, ip, username, password, power_control="restapi2", accept_all=True, ) self.assertEqual(2, mock_create_node.call_count) self.expectThat( mock_create_node, MockCallsMatch( call( fake_server_0.get_fake_macs(), "amd64", "sm15k", { "power_control": "restapi2", "system_id": "0", "power_address": ip, "power_pass": password, "power_user": username, }, domain=None, ), call( fake_server_1.get_fake_macs(), "amd64", "sm15k", { "power_control": "restapi2", "system_id": "1", "power_address": ip, "power_pass": password, "power_user": username, }, domain=None, ), ), ) self.expectThat(mock_commission_node, MockCalledWith(system_id, user))