def test_encode_multipart_data_produces_bytes(self):
     data = {
         factory.make_string(): factory.make_string().encode('ascii'),
     }
     files = {
         factory.make_string(): (
             BytesIO(factory.make_string().encode('ascii'))),
     }
     body, headers = encode_multipart_data(data, files)
     self.assertIsInstance(body, bytes)
Exemple #2
0
 def test__returns_standard_output(self):
     output = factory.make_string().encode("ascii")
     self.assertEqual(output, call_and_check(['/bin/echo', '-n', output]))
Exemple #3
0
 def test__compares_in_text_mode_when_encoding_supplied(self):
     contents = factory.make_string()  # text
     filename = self.make_file(contents=contents.encode("ascii"))
     self.assertThat(filename,
                     FileContains(contents=contents, encoding="ascii"))
Exemple #4
0
 def test__returns_none_if_attribute_exists(self):
     attribute = factory.make_string(3, prefix="attr")
     setattr(self, attribute, factory.make_name("value"))
     matcher = HasAttribute(attribute)
     result = matcher.match(self)
     self.assertIsNone(result)
Exemple #5
0
 def test_exits_when_file_has_no_options_block(self):
     content = factory.make_string()
     self.assertContentFailsWithMessage(content,
                                        "Can't find options {} block")
Exemple #6
0
 def test_read_snippet_reads_snippet_file(self):
     contents = factory.make_string()
     snippet = self.make_file(contents=contents)
     self.assertEqual(
         contents,
         read_snippet(os.path.dirname(snippet), os.path.basename(snippet)))
Exemple #7
0
 def test_doesnt_affect_general_logger_class(self):
     self.patch(logging, 'Formatter')
     name = factory.make_string()
     get_maas_logger(name)
     self.assertIsNot(MAASLogger, logging.getLoggerClass())
Exemple #8
0
 def test_sets_logger_name(self):
     self.patch(_maaslog, 'SysLogHandler')
     self.patch(logging, 'Formatter')
     name = factory.make_string()
     maaslog = get_maas_logger(name)
     self.assertEqual("maas.%s" % name, maaslog.name)
Exemple #9
0
 def test_rejects_non_bytes_contents(self):
     self.assertRaises(TypeError, sudo_write_file, self.make_file(),
                       factory.make_string())
Exemple #10
0
 def test_atomic_write_rejects_non_bytes_contents(self):
     self.assertRaises(TypeError, atomic_write, factory.make_string(),
                       factory.make_string())
Exemple #11
0
    def test_report_power_state_reports_all_exceptions(self):
        logger_twisted = self.useFixture(TwistedLoggerFixture())
        logger_maaslog = self.useFixture(FakeLogger("maas"))

        # Avoid threads here.
        self.patch(power, "deferToThread", maybeDeferred)

        exception_type = factory.make_exception_type()
        exception_message = factory.make_string()
        exception = exception_type(exception_message)

        # Pretend the query always fails with `exception`.
        query = self.patch_autospec(power, self.func)
        query.side_effect = always_fail_with(exception)

        # Intercept calls to power_state_update() and send_node_event().
        power_state_update = self.patch_autospec(power, "power_state_update")
        power_state_update.return_value = succeed(None)
        send_node_event = self.patch_autospec(power, "send_node_event")
        send_node_event.return_value = succeed(None)

        self.patch(self.power_driver,
                   "detect_missing_packages").return_value = []

        system_id = factory.make_name("system_id")
        hostname = factory.make_name("hostname")
        context = sentinel.context
        clock = Clock()

        d = power.get_power_state(system_id, hostname, self.power_type,
                                  context, clock)
        d = power.report_power_state(d, system_id, hostname)

        # Crank through some number of retries.
        for wait in self.waits:
            self.assertFalse(d.called)
            clock.advance(wait)
        self.assertTrue(d.called)

        # Finally the exception from the query is raised.
        self.assertRaises(exception_type, extract_result, d)

        # The broken power query function patched earlier was called the same
        # number of times as there are steps in the default waiting policy.
        expected_call = call(system_id, hostname, self.power_type, context)
        expected_calls = [expected_call] * self.calls
        self.assertThat(query, MockCallsMatch(*expected_calls))

        expected_message = "%s: Power state could not be queried: %s" % (
            hostname,
            exception_message,
        )

        # An attempt was made to report the failure to the region.
        self.assertThat(power_state_update,
                        MockCalledOnceWith(system_id, "error"))
        # An attempt was made to log a node event with details.
        self.assertThat(
            send_node_event,
            MockCalledOnceWith(
                EVENT_TYPES.NODE_POWER_QUERY_FAILED,
                system_id,
                hostname,
                exception_message,
            ),
        )

        # Nothing was logged to the Twisted log.
        self.assertEqual("", logger_twisted.output)
        # A brief message is written to maaslog.
        self.assertEqual(expected_message + "\n", logger_maaslog.output)
Exemple #12
0
 def test_mismatching_content_is_compared_False(self):
     content = factory.make_string()
     storage, meta_file = self.make_meta_file()
     self.assertFalse(boot_resources.meta_contains(storage, content))
    def test_accepts_all_args(self):
        all_test_arguments = cluster_config_command.all_arguments

        default_arg_values = {
            "--region-url": None,
            "--uuid": None,
            "--init": False,
            "--tftp-port": None,
            "--tftp-root": None,
            "--debug": None,
        }

        failures = {}

        # Try all cardinalities of combinations of arguments
        for r in range(len(all_test_arguments) + 1):
            for test_arg_names in combinations(all_test_arguments, r):
                test_values = {
                    "--region-url": factory.make_simple_http_url(),
                    "--uuid": str(uuid.uuid4()),
                    "--init": "",
                    "--tftp-port": str(factory.pick_port()),
                    "--tftp-root": factory.make_string(),
                    "--debug": str(factory.pick_bool()),
                }

                # Build a query dictionary for the given combination of args
                args_under_test = []
                for param_name in test_arg_names:
                    args_under_test.append(param_name)
                    if param_name != "--init":
                        args_under_test.append(test_values[param_name])

                parser = ArgumentParser()
                cluster_config_command.add_arguments(parser)

                # If both init and uuid are passed, argparse will generate
                # a nice ArgumentError exception, which unfortunately,
                # gets caught and sent to exit.
                if "--init" in test_arg_names and "--uuid" in test_arg_names:
                    expected_exception = ExpectedException(SystemExit, "2")
                    with expected_exception, patch("sys.stderr"):
                        parser.parse_known_args(args_under_test)

                else:
                    # Otherwise, parsed args with defaults as usual
                    observed_args = vars(parser.parse_args(args_under_test))

                    expected_args = {}
                    for param_name in all_test_arguments:
                        parsed_param_name = param_name[2:].replace("-", "_")

                        if param_name not in test_arg_names:
                            expected_args[
                                parsed_param_name] = default_arg_values[
                                    param_name]
                        else:
                            expected_args[parsed_param_name] = observed_args[
                                parsed_param_name]

                    if expected_args != observed_args:
                        failures[str(test_arg_names)] = {
                            "expected_args": expected_args,
                            "observed_args": observed_args,
                        }

        error_message = io.StringIO()
        error_message.write("One or more key / value argument list(s)"
                            "passed in the query string (expected_args)"
                            "to the API do not match the values in "
                            "the returned query string. This "
                            "means that some arguments were "
                            "dropped / added / changed by the "
                            "the function, which is incorrect "
                            "behavior. The list of incorrect "
                            "arguments is as follows: \n")
        pp = pprint.PrettyPrinter(depth=3, stream=error_message)
        pp.pprint(failures)
        self.assertDictEqual({}, failures, error_message.getvalue())
Exemple #14
0
 def test__first_encrypt_caches_psk(self):
     self.write_secret()
     self.assertIsNone(security._fernet_psk)
     testdata = factory.make_string()
     fernet_encrypt_psk(testdata)
     self.assertIsNotNone(security._fernet_psk)
Exemple #15
0
 def test_encode_multipart_data_closes_with_closing_boundary_line(self):
     data = {"foo": factory.make_string().encode("ascii")}
     files = {"bar": BytesIO(factory.make_string().encode("ascii"))}
     body, headers = encode_multipart_data(data, files)
     self.assertTrue(body.endswith("--"))
 def test_encode_multipart_data_closes_with_closing_boundary_line(self):
     data = {b'foo': factory.make_string().encode('ascii')}
     files = {b'bar': BytesIO(factory.make_string().encode('ascii'))}
     body, headers = encode_multipart_data(data, files)
     self.assertThat(body, EndsWith(b'--'))
Exemple #17
0
 def test_deferredDHCPRequestErrback_ignores_cancelled(self):
     logger = self.useFixture(TwistedLoggerFixture())
     monitor = DHCPRequestMonitor("lo")
     error = factory.make_string()
     monitor.deferredDHCPRequestErrback(make_Failure(CancelledError, error))
     self.assertThat(logger.output, DocTestMatches(""))
Exemple #18
0
    def test_uses_prefix(self):
        prefix = factory.make_string(3)
        with tempdir(prefix=prefix) as directory:
            pass

        self.assertThat(os.path.basename(directory), StartsWith(prefix))
Exemple #19
0
 def test_returns_MAASLogger_instances(self):
     self.patch(_maaslog, 'SysLogHandler')
     self.patch(logging, 'Formatter')
     name = factory.make_string()
     maaslog = get_maas_logger(name)
     self.assertIsInstance(maaslog, MAASLogger)
Exemple #20
0
    def test_uses_suffix(self):
        suffix = factory.make_string(3)
        with tempdir(suffix=suffix) as directory:
            pass

        self.assertThat(os.path.basename(directory), EndsWith(suffix))
Exemple #21
0
 def test_general_logger_class_accepts_exceptions(self):
     self.patch(logging, 'Formatter')
     name = factory.make_string()
     get_maas_logger(name)
     other_logger = logging.getLogger()
     self.assertIsNone(other_logger.exception(factory.make_string()))
Exemple #22
0
 def test_reads_file(self):
     text = factory.make_string()
     self.assertEqual(text, read_text_file(self.make_file(contents=text)))
Exemple #23
0
 def test_strip_name_leaves_simple_names_intact(self):
     simple_name = factory.make_string()
     self.assertEqual(simple_name, strip_name(simple_name))
Exemple #24
0
 def test_creates_file(self):
     path = os.path.join(self.make_dir(), factory.make_name('text'))
     text = factory.make_string()
     write_text_file(path, text)
     self.assertThat(path, FileContains(text, encoding="ascii"))
Exemple #25
0
 def test_write_config_errors_if_unexpected_exception(self):
     dnsconfig = DNSConfig()
     exception = IOError(errno.EBUSY, factory.make_string())
     self.patch(config, "atomic_write", Mock(side_effect=exception))
     self.assertRaises(IOError, dnsconfig.write_config)
Exemple #26
0
 def test_overwrites_file(self):
     path = self.make_file(contents="original text")
     text = factory.make_string()
     write_text_file(path, text)
     self.assertThat(path, FileContains(text, encoding="ascii"))
Exemple #27
0
 def test__returns_mismatch_if_attribute_does_not_exist(self):
     attribute = factory.make_string(3, prefix="attr")
     matcher = HasAttribute(attribute)
     result = matcher.match(self)
     self.assertMismatch(result,
                         " does not have a %r attribute" % attribute)
Exemple #28
0
 def test_atomic_write_overwrites_dest_file(self):
     content = factory.make_bytes()
     filename = self.make_file(contents=factory.make_string())
     atomic_write(content, filename)
     self.assertThat(filename, FileContains(content))
Exemple #29
0
 def test_matches_equal_strings(self):
     contents = factory.make_string()
     self.assertThat(contents, TextEquals(contents))
Exemple #30
0
 def test_atomic_write_writes_file_if_no_file_present(self):
     filename = os.path.join(self.make_dir(), factory.make_string())
     content = factory.make_bytes()
     atomic_write(content, filename, overwrite=False)
     self.assertThat(filename, FileContains(content))
 def test_deletes_maas_id_file(self):
     self.useFixture(MAASIDFixture(factory.make_string()))
     url = factory.make_simple_http_url()
     secret = factory.make_bytes()
     register_command.run(self.make_args(url=url, secret=to_hex(secret)))
     self.assertIsNone(get_maas_id())
Exemple #32
0
 def test_Redirect_produces_redirect_to_given_URL(self):
     target = factory.make_string()
     exception = Redirect(target)
     response = exception.make_http_response()
     self.assertEqual(target, extract_redirect(response))