Exemple #1
0
    def test_returns_mismatch_when_zero_calls(self):
        mock = Mock()

        matcher = MockCalledOnce()
        result = matcher.match(mock)
        self.assertMismatch(result,
                            "Expected to be called once. Called 0 times.")
Exemple #2
0
    def test_event_type_is_registered_on_first_call_only(self):
        protocol, connecting = self.patch_rpc_methods(side_effect=[{}, {}])
        self.addCleanup((yield connecting))

        ip_address = factory.make_ip_address()
        description = factory.make_name("description")
        event_name = random.choice(list(map_enum(EVENT_TYPES)))
        event_detail = EVENT_DETAILS[event_name]
        event_hub = NodeEventHub()

        # On the first call, the event type is registered before the log is
        # sent to the region.
        yield event_hub.logByIP(event_name, ip_address, description)
        self.assertThat(
            protocol.RegisterEventType,
            MockCalledOnceWith(
                ANY,
                name=event_name,
                description=event_detail.description,
                level=event_detail.level,
            ),
        )
        self.assertThat(protocol.SendEventIPAddress, MockCalledOnce())

        # Reset RPC call handlers.
        protocol.RegisterEventType.reset_mock()
        protocol.SendEventIPAddress.reset_mock()

        # On the second call, the event type is known to be registered, so the
        # log is sent to the region immediately.
        yield event_hub.logByIP(event_name, ip_address, description)
        self.assertThat(protocol.RegisterEventType, MockNotCalled())
        self.assertThat(protocol.SendEventIPAddress, MockCalledOnce())
Exemple #3
0
    def test_returns_none_when_matches(self):
        mock = Mock()
        mock(1, 2, frob=5, nob=6)

        matcher = MockCalledOnce()
        result = matcher.match(mock)
        self.assertIsNone(result)
Exemple #4
0
    def test_returns_mismatch_when_multiple_calls(self):
        mock = Mock()
        mock(1, 2, frob=5, nob=6)
        mock(1, 2, frob=5, nob=6)

        matcher = MockCalledOnce()
        result = matcher.match(mock)
        self.assertMismatch(result,
                            "Expected to be called once. Called 2 times.")
 def test_configure(self):
     mock_set_ipmi_lan_channel_settings = self.patch(
         self.ipmi, "_set_ipmi_lan_channel_settings")
     mock_config_cipher_suite_id = self.patch(self.ipmi,
                                              "_config_cipher_suite_id")
     mock_config_kg = self.patch(self.ipmi, "_config_kg")
     self.ipmi.configure()
     self.assertThat(mock_set_ipmi_lan_channel_settings, MockCalledOnce())
     self.assertThat(mock_config_cipher_suite_id, MockCalledOnce())
     self.assertThat(mock_config_kg, MockCalledOnce())
Exemple #6
0
 def test__forwards_to_console(self):
     stdout = self.patch(maas_api_helper.sys.stdout, 'write')
     stderr = self.patch(maas_api_helper.sys.stderr, 'write')
     stdout_flush = self.patch(maas_api_helper.sys.stdout, 'flush')
     stderr_flush = self.patch(maas_api_helper.sys.stderr, 'flush')
     self.isatty.return_value = True
     proc = Popen(
         'echo "stdout"; echo "stderr" 1>&2', stdout=PIPE, stderr=PIPE,
         shell=True)
     self.capture(proc)
     self.assertThat(stdout, MockCalledOnceWith("stdout\n"))
     self.assertThat(stderr, MockCalledOnceWith("stderr\n"))
     self.assertThat(stdout_flush, MockCalledOnce())
     self.assertThat(stderr_flush, MockCalledOnce())
    def test_runs_if_not_on_vm(self):
        self.patch(bmc_config.os.environ, "get")
        self.patch(bmc_config.os.path, "exists").return_value = False
        self.mock_check_call.side_effect = CalledProcessError(
            1, ["systemd-detect-virt", "-q"])
        mock_run = self.patch(bmc_config, "run")
        mock_detect_and_configure = self.patch(bmc_config,
                                               "detect_and_configure")

        bmc_config.main()

        self.assertThat(
            self.mock_check_call,
            MockCalledOnceWith(["systemd-detect-virt", "-q"], timeout=60),
        )
        self.assertThat(
            mock_run,
            MockCallsMatch(
                call(["sudo", "-E", "modprobe", "ipmi_msghandler"],
                     timeout=60),
                call(["sudo", "-E", "modprobe", "ipmi_devintf"], timeout=60),
                call(["sudo", "-E", "modprobe", "ipmi_si"], timeout=60),
                call(["sudo", "-E", "modprobe", "ipmi_ssif"], timeout=60),
                call(["sudo", "-E", "udevadm", "settle"], timeout=60),
            ),
        )
        self.assertThat(mock_detect_and_configure, MockCalledOnce())
Exemple #8
0
    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())
Exemple #9
0
    def test__returns_false_when_no_new_images(self):
        # Stop import_images() from actually doing anything.
        self.patch(boot_resources, 'maaslog')
        fake_download_all_image_descriptions = self.patch(
            boot_resources, 'download_all_image_descriptions')
        fake_image_descriptions = MagicMock()
        fake_image_descriptions.is_empty.return_value = False
        fake_download_all_image_descriptions.return_value = (
            fake_image_descriptions)
        self.patch(boot_resources, 'meta_contains').return_value = True
        fake_update_iscsi_targets = self.patch(boot_resources,
                                               'update_iscsi_targets')

        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")],
                    },
                ],
            },
        ],
        self.assertFalse(boot_resources.import_images(sources))
        self.assertThat(fake_update_iscsi_targets, 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())
Exemple #11
0
 def test_list_tokens(self):
     token1_name = "Test Token 1"
     mock_create_audit_event = self.patch(account_module,
                                          "create_audit_event")
     response_creation = self.client.post(
         reverse("account_handler"),
         {
             "op": "create_authorisation_token",
             "name": token1_name
         },
     )
     parsed_creation_response = json_load_bytes(response_creation.content)
     response = self.client.get(reverse("account_handler"),
                                {"op": "list_authorisation_tokens"})
     parsed_list_response = json_load_bytes(response.content)
     self.assertEqual(len(json_load_bytes(response.content)), 2)
     for token in parsed_list_response:
         if token["name"] == token1_name:
             token_fields = token["token"].split(":")
             self.assertEqual(token_fields[0],
                              parsed_creation_response["consumer_key"])
             self.assertEqual(token_fields[1],
                              parsed_creation_response["token_key"])
             self.assertEqual(token_fields[2],
                              parsed_creation_response["token_secret"])
     self.assertThat(mock_create_audit_event, MockCalledOnce())
Exemple #12
0
 def test__tryUpdate_updates_syslog_server(self):
     service = syslog.RegionSyslogService(reactor)
     port, peers = yield deferToDatabase(self.make_example_configuration)
     write_config = self.patch_autospec(syslog, "write_config")
     restartService = self.patch_autospec(service_monitor, "restartService")
     yield service._tryUpdate()
     self.assertThat(
         write_config,
         MockCalledOnceWith(
             True,
             Matches(
                 ContainsAll(
                     [
                         {
                             "ip": service._formatIP(ip),
                             "name": node.hostname,
                         }
                         for node, ip in peers
                     ]
                 )
             ),
             port=port,
         ),
     )
     self.assertThat(restartService, MockCalledOnceWith("syslog_region"))
     # If the configuration has not changed then a second call to
     # `_tryUpdate` does not result in another call to `write_config`.
     yield service._tryUpdate()
     self.assertThat(write_config, MockCalledOnce())
     self.assertThat(restartService, MockCalledOnceWith("syslog_region"))
    def test_get_bmc_ip(self):
        self.mock_check_output.return_value = (
            b"8: eth0    inet fe80::ff:fe00:2/64 brd 10.0.0.255 scope global "
            b"eth0\\       valid_lft forever preferred_lft forever")
        mock_ssh_client = self.patch(bmc_config, "SSHClient")
        mock_client = mock_ssh_client.return_value
        mock_client.set_missing_host_key_policy = MagicMock()
        mock_client.connect = MagicMock()
        mock_stdout = MagicMock()
        mock_stdout.read.return_value = (
            b"1: lo    inet 127.0.0.1/8 scope host lo\\       "
            b"valid_lft forever preferred_lft forever"
            b"\n"
            b"8: eth0    inet 10.0.0.10/24 brd 10.0.0.255 scope global "
            b"eth0\\       valid_lft forever preferred_lft forever"
            b"\n"
            b"10: eth1    inet 192.168.122.78/24 brd 192.168.122.255 scope "
            b"global dynamic eth1\\       valid_lft 3348sec preferred_lft "
            b"3348sec")
        mock_client.exec_command.return_value = None, mock_stdout, None

        self.assertEquals("10.0.0.10", self.wedge.get_bmc_ip())
        # Call multiple times to verify caching
        self.assertEquals(self.wedge.get_bmc_ip(), self.wedge.get_bmc_ip())
        self.assertThat(mock_ssh_client, MockCalledOnce())
        self.assertThat(
            mock_client.set_missing_host_key_policy,
            MockCalledOnceWith(bmc_config.IgnoreHostKeyPolicy),
        )
        self.assertThat(
            mock_client.connect,
            MockCalledOnceWith("fe80::1%eth0",
                               username="******",
                               password="******"),
        )
    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_cleans_up_on_failure(self):
        # Stop import_images() from actually doing anything.
        self.patch(boot_resources, "maaslog")
        fake_download_all_image_descriptions = self.patch(
            boot_resources, "download_all_image_descriptions")
        fake_image_descriptions = MagicMock()
        fake_image_descriptions.is_empty.return_value = False
        fake_download_all_image_descriptions.return_value = (
            fake_image_descriptions)
        self.patch(boot_resources, "meta_contains").return_value = False
        self.patch(boot_resources, "map_products")
        self.patch(boot_resources,
                   "download_all_boot_resources").side_effect = Exception
        fake_cleanup_snapshots_and_cache = self.patch(
            boot_resources, "cleanup_snapshots_and_cache")

        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")],
            }],
        }], )
        self.assertRaises(Exception, boot_resources.import_images, sources)
        self.assertThat(fake_cleanup_snapshots_and_cache, MockCalledOnce())
Exemple #16
0
    def test_signal_formats_params_with_moonshot_power_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')
        power_type = 'moonshot'
        power_params = OrderedDict([
            ('power_user', factory.make_name('power_user')),
            ('power_pass', factory.make_name('power_pass')),
            ('power_address', factory.make_url()),
            ('power_hwaddress', factory.make_name('power_hwaddress')),
        ])

        # None used for url and creds as we're not actually sending data.
        maas_api_helper.signal(
            None, None, status, power_type=power_type,
            power_params=','.join([value for value in power_params.values()]))

        # XXX ltrager 2017-01-18 - The power_parameters JSON dump breaks
        # MockCalledWith.
        self.assertDictEqual(
            mock_encode_multipart_data.call_args[0][0],
            {
                b'op': b'signal',
                b'status': status.encode('utf-8'),
                b'power_type': power_type.encode('utf-8'),
                b'power_parameters': json.dumps(power_params).encode(),
            })
        self.assertThat(mock_geturl, MockCalledOnce())
    def test_finds_nothing(self):
        bmc_config_path = os.path.join(
            self.useFixture(TempDirectory()).path, "bmc-config.yaml")
        args = MagicMock()
        args.user = factory.make_name("user")
        args.password = factory.make_name("password")
        self.patch(bmc_config.HPMoonshot, "detected").return_value = False
        self.patch(bmc_config.IPMI, "detected").return_value = False
        self.patch(bmc_config.Wedge, "detected").return_value = False

        bmc_config.detect_and_configure(args, bmc_config_path)

        self.assertFalse(os.path.exists(bmc_config_path))
        self.assertThat(bmc_config.HPMoonshot.detected, MockCalledOnce())
        self.assertThat(bmc_config.IPMI.detected, MockCalledOnce())
        self.assertThat(bmc_config.Wedge.detected, MockCalledOnce())
Exemple #18
0
    def test__compose_with_commissioning(self):
        request = MagicMock()
        pod = make_pod_with_hints()

        # Mock the RPC client.
        client = MagicMock()
        mock_getClient = self.patch(pods_module, "getClientFromIdentifiers")
        mock_getClient.return_value = succeed(client)

        # Mock the result of the composed machine.
        composed_machine, pod_hints = self.make_compose_machine_result(pod)
        mock_compose_machine = self.patch(pods_module, "compose_machine")
        mock_compose_machine.return_value = succeed(
            (composed_machine, pod_hints))

        # Mock start_commissioning so it doesn't use post commit hooks.
        mock_commissioning = self.patch(Machine, "start_commissioning")

        form = ComposeMachineForm(data={}, request=request, pod=pod)
        self.assertTrue(form.is_valid())
        created_machine = form.compose()
        self.assertThat(created_machine, MatchesAll(
            IsInstance(Machine),
            MatchesStructure(
                cpu_count=Equals(1),
                memory=Equals(1024),
                cpu_speed=Equals(300))))
        self.assertThat(mock_commissioning, MockCalledOnce())
    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())
Exemple #20
0
    def test_link_bootloader_logs_missing_simplestream_file(self):
        method = FakeBootMethod()
        mock_maaslog = self.patch(maaslog, 'error')
        mock_try_send_rack_event = self.patch(boot, 'try_send_rack_event')
        with tempdir() as tmp:
            stream_path = os.path.join(tmp, 'bootloader',
                                       method.bios_boot_method,
                                       method.bootloader_arches[0])
            os.makedirs(stream_path)
            for bootloader_file in method.bootloader_files[1:]:
                factory.make_file(stream_path, bootloader_file)

            method.link_bootloader(tmp)

            self.assertThat(mock_maaslog, MockCalledOnce())
            self.assertThat(mock_try_send_rack_event, MockCalledOnce())
    def test_mark_nodes_failed_after_missing_timeout_heartbeat(self):
        node, script_set = self.make_node()
        script_set.last_ping = datetime.now() - timedelta(minutes=11)
        script_set.save()
        script_results = [
            factory.make_ScriptResult(
                script_set=script_set, status=SCRIPT_STATUS.PENDING)
            for _ in range(3)
        ]

        mark_nodes_failed_after_missing_script_timeout()
        node = reload_object(node)

        self.assertEquals(self.failed_status, node.status)
        self.assertEquals(
            "Node has not been heard from for the last 10 minutes",
            node.error_description)
        self.assertIn(
            call(
                "%s: Has not been heard from for the last 10 minutes" %
                node.hostname),
            self.maaslog.call_args_list)
        if node.enable_ssh:
            self.assertThat(self.mock_stop, MockNotCalled())
        else:
            self.assertThat(self.mock_stop, MockCalledOnce())
            self.assertIn(
                call("%s: Stopped because SSH is disabled" % node.hostname),
                self.maaslog.call_args_list)
        for script_result in script_results:
            self.assertEquals(
                SCRIPT_STATUS.TIMEDOUT, reload_object(script_result).status)
 def test_generate_rsa_if_needed_waits_for_creation(self):
     mock_isfile = self.patch(maas_certificates.os.path, "isfile")
     mock_isfile.side_effect = [False, False, True, True]
     mock_sleep = self.patch(maas_certificates, "sleep")
     with NamedLock("RSA"):
         self.assertTrue(maas_certificates.generate_rsa_keys_if_needed())
     self.assertThat(mock_sleep, MockCalledOnce())
Exemple #23
0
 def test_list_tokens(self):
     token1_name = "Test Token 1"
     mock_create_audit_event = self.patch(
         account_module, 'create_audit_event')
     response_creation = self.client.post(
         reverse('account_handler'), {
             'op': 'create_authorisation_token',
             'name': token1_name
         })
     parsed_creation_response = json_load_bytes(response_creation.content)
     response = self.client.get(
         reverse('account_handler'), {
             'op': 'list_authorisation_tokens'
         })
     parsed_list_response = json_load_bytes(response.content)
     self.assertEqual(len(json_load_bytes(response.content)), 2)
     for token in parsed_list_response:
         if token['name'] == token1_name:
             token_fields = token['token'].split(":")
             self.assertEqual(
                 token_fields[0],
                 parsed_creation_response['consumer_key'])
             self.assertEqual(
                 token_fields[1],
                 parsed_creation_response['token_key'])
             self.assertEqual(
                 token_fields[2],
                 parsed_creation_response['token_secret'])
     self.assertThat(mock_create_audit_event, MockCalledOnce())
Exemple #24
0
    def test_link_bootloader_logs_missing_previous_downloaded_files(self):
        method = FakeBootMethod()
        mock_maaslog = self.patch(maaslog, "error")
        mock_try_send_rack_event = self.patch(boot, "try_send_rack_event")
        with tempdir() as tmp:
            new_dir = os.path.join(tmp, "new")
            current_dir = os.path.join(tmp, "current")
            os.makedirs(new_dir)
            os.makedirs(current_dir)
            for bootloader_file in method.bootloader_files[1:]:
                factory.make_file(current_dir, bootloader_file)

            method.link_bootloader(new_dir)

            self.assertThat(mock_maaslog, MockCalledOnce())
            self.assertThat(mock_try_send_rack_event, MockCalledOnce())
Exemple #25
0
 def test__output(self):
     self.assertEquals(self.output, smartctl.run_storcli(self.args, True))
     self.assertThat(
         self.mock_check_output,
         MockCalledOnceWith(['sudo', '-n', 'storcli64'] + self.args,
                            timeout=smartctl.TIMEOUT))
     self.assertThat(self.mock_print, MockCalledOnce())
    def test_skips_if_bmc_config_exists(self):
        self.patch(bmc_config.os.environ, "get")
        self.patch(bmc_config.os.path, "exists").return_value = True
        mock_exit_skipped = self.patch(bmc_config, "exit_skipped")

        bmc_config.main()

        self.assertThat(mock_exit_skipped, MockCalledOnce())
Exemple #27
0
 def test_unavailable(self):
     mock_run_smartctl = self.patch(smartctl, "run_smartctl")
     mock_run_smartctl.return_value = ("Product: %s\n"
                                       "SMART support is: Unavailable\n" %
                                       factory.make_name("product"))
     mock_exit_skipped = self.patch(smartctl, "exit_skipped")
     smartctl.check_SMART_support(factory.make_name("blockdevice"))
     self.assertThat(mock_exit_skipped, MockCalledOnce())
Exemple #28
0
 def test_link_bootloader_logs_missing_bootloader_files(self):
     method = UEFIAMD64BootMethod()
     self.patch(grub_module.os.path, "exists").return_value = False
     mock_maaslog = self.patch(grub_module.maaslog, "error")
     bootloader_dir = "/var/lib/maas/boot-resources/%s" % factory.make_name(
         "snapshot")
     method._find_and_copy_bootloaders(bootloader_dir)
     self.assertThat(mock_maaslog, MockCalledOnce())
Exemple #29
0
 def test_link_bootloader_logs_missing_bootloader_files(self):
     method = UEFIAMD64BootMethod()
     self.patch(uefi_amd64_module.os.path, 'exists').return_value = False
     mock_maaslog = self.patch(uefi_amd64_module.maaslog, 'error')
     bootloader_dir = ('/var/lib/maas/boot-resources/%s' %
                       factory.make_name('snapshot'))
     method._find_and_copy_bootloaders(bootloader_dir)
     self.assertThat(mock_maaslog, MockCalledOnce())
Exemple #30
0
 def test__unavailable(self):
     mock_run_smartctl = self.patch(smartctl, 'run_smartctl')
     mock_run_smartctl.return_value = ('Product: %s\n'
                                       'SMART support is: Unavailable\n' %
                                       factory.make_name('product'))
     mock_exit_skipped = self.patch(smartctl, 'exit_skipped')
     smartctl.check_SMART_support(factory.make_name('blockdevice'))
     self.assertThat(mock_exit_skipped, MockCalledOnce())