Example #1
0
    def exec_readlines_test_filter_stderr(self):
        """Test execReadlines and filter_stderr."""

        # Test that stderr is normally included
        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two" >&2
echo "three"
exit 0
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(StopIteration, rl_iterator.__next__)

        # Test that filter stderr removes the middle line
        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two" >&2
echo "three"
exit 0
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name], filter_stderr=True)
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(StopIteration, rl_iterator.__next__)
Example #2
0
    def exec_readlines_test_filter_stderr(self):
        """Test execReadlines and filter_stderr."""

        # Test that stderr is normally included
        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two" >&2
echo "three"
exit 0
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(StopIteration, rl_iterator.__next__)

        # Test that filter stderr removes the middle line
        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two" >&2
echo "three"
exit 0
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name], filter_stderr=True)
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(StopIteration, rl_iterator.__next__)
Example #3
0
    def exec_readlines_test_signals(self):
        """Test execReadlines and signal receipt."""

        # ignored signal
        old_HUP_handler = signal.signal(signal.SIGHUP, signal.SIG_IGN)
        try:
            with tempfile.NamedTemporaryFile(mode="wt") as testscript:
                testscript.write(
                    """#!/bin/sh
echo "one"
kill -HUP $PPID
echo "two"
echo -n "three"
exit 0
"""
                )
                testscript.flush()

                with timer(5):
                    rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                    self.assertEqual(next(rl_iterator), "one")
                    self.assertEqual(next(rl_iterator), "two")
                    self.assertEqual(next(rl_iterator), "three")
                    self.assertRaises(StopIteration, rl_iterator.__next__)
        finally:
            signal.signal(signal.SIGHUP, old_HUP_handler)

        # caught signal
        def _hup_handler(signum, frame):
            pass

        old_HUP_handler = signal.signal(signal.SIGHUP, _hup_handler)
        try:
            with tempfile.NamedTemporaryFile(mode="wt") as testscript:
                testscript.write(
                    """#!/bin/sh
echo "one"
kill -HUP $PPID
echo "two"
echo -n "three"
exit 0
"""
                )
                testscript.flush()

                with timer(5):
                    rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                    self.assertEqual(next(rl_iterator), "one")
                    self.assertEqual(next(rl_iterator), "two")
                    self.assertEqual(next(rl_iterator), "three")
                    self.assertRaises(StopIteration, rl_iterator.__next__)
        finally:
            signal.signal(signal.SIGHUP, old_HUP_handler)
Example #4
0
    def exec_readlines_test(self):
        """Test execReadlines."""

        # test no lines are returned
        self.assertEqual(list(iutil.execReadlines("true", [])), [])

        # test some lines are returned
        self.assertGreater(len(list(iutil.execReadlines("ls", ["--help"]))), 0)

        # check that it always returns an iterator for both
        # if there is some output and if there isn't any
        self.assertTrue(hasattr(iutil.execReadlines("ls", ["--help"]), "__iter__"))
        self.assertTrue(hasattr(iutil.execReadlines("true", []), "__iter__"))
Example #5
0
    def exec_readlines_test(self):
        """Test execReadlines."""

        # test no lines are returned
        self.assertEqual(list(iutil.execReadlines("true", [])), [])

        # test some lines are returned
        self.assertGreater(len(list(iutil.execReadlines("ls", ["--help"]))), 0)

        # check that it always returns an iterator for both
        # if there is some output and if there isn't any
        self.assertTrue(hasattr(iutil.execReadlines("ls", ["--help"]), "__iter__"))
        self.assertTrue(hasattr(iutil.execReadlines("true", []), "__iter__"))
Example #6
0
    def exec_readlines_test_signals(self):
        """Test execReadlines and signal receipt."""

        # ignored signal
        old_HUP_handler = signal.signal(signal.SIGHUP, signal.SIG_IGN)
        try:
            with tempfile.NamedTemporaryFile(mode="wt") as testscript:
                testscript.write("""#!/bin/sh
echo "one"
kill -HUP $PPID
echo "two"
echo -n "three"
exit 0
""")
                testscript.flush()

                with timer(5):
                    rl_iterator = iutil.execReadlines("/bin/sh",
                                                      [testscript.name])
                    self.assertEqual(next(rl_iterator), "one")
                    self.assertEqual(next(rl_iterator), "two")
                    self.assertEqual(next(rl_iterator), "three")
                    self.assertRaises(StopIteration, rl_iterator.__next__)
        finally:
            signal.signal(signal.SIGHUP, old_HUP_handler)

        # caught signal
        def _hup_handler(signum, frame):
            pass

        old_HUP_handler = signal.signal(signal.SIGHUP, _hup_handler)
        try:
            with tempfile.NamedTemporaryFile(mode="wt") as testscript:
                testscript.write("""#!/bin/sh
echo "one"
kill -HUP $PPID
echo "two"
echo -n "three"
exit 0
""")
                testscript.flush()

                with timer(5):
                    rl_iterator = iutil.execReadlines("/bin/sh",
                                                      [testscript.name])
                    self.assertEqual(next(rl_iterator), "one")
                    self.assertEqual(next(rl_iterator), "two")
                    self.assertEqual(next(rl_iterator), "three")
                    self.assertRaises(StopIteration, rl_iterator.__next__)
        finally:
            signal.signal(signal.SIGHUP, old_HUP_handler)
Example #7
0
    def exec_readlines_test(self):
        """Test execReadlines."""

        # test no lines are returned
        self.assertEqual(list(iutil.execReadlines("true", [])), [])

        # test some lines are returned
        self.assertGreater(len(list(iutil.execReadlines("ls", ["--help"]))), 0)

        # check that it always returns a generator for both
        # if there is some output and if there isn't any
        self.assertIsInstance(iutil.execReadlines("ls", ["--help"]),
                              types.GeneratorType)
        self.assertIsInstance(iutil.execReadlines("true", []),
                              types.GeneratorType)
Example #8
0
    def exec_readlines_auto_kill_test(self):
        """Test execReadlines with reading only part of the output"""

        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write("""#!/bin/sh
# Output forever
while true; do
echo hey
done
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])

                # Save the process context
                proc = rl_iterator._proc

                # Read two lines worth
                self.assertEqual(next(rl_iterator), "hey")
                self.assertEqual(next(rl_iterator), "hey")

                # Delete the iterator and wait for the process to be killed
                del rl_iterator
                proc.communicate()

            # Check that the process is gone
            self.assertIsNotNone(proc.poll())
Example #9
0
    def exec_readlines_auto_kill_test(self):
        """Test execReadlines with reading only part of the output"""

        with tempfile.NamedTemporaryFile() as testscript:
            testscript.write("""#!/bin/sh
# Output forever
while true; do
echo hey
done
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])

                # Save the process context
                proc = rl_iterator._proc

                # Read two lines worth
                self.assertEqual(rl_iterator.next(), "hey")
                self.assertEqual(rl_iterator.next(), "hey")

                # Delete the iterator and wait for the process to be killed
                del rl_iterator
                proc.communicate()

            # Check that the process is gone
            self.assertIsNotNone(proc.poll())
Example #10
0
 def get_doc_type(file_path):
     try:
         for line in execReadlines("oscap", ["info", file_path]):
             if line.startswith("Document type:"):
                 _prefix, _sep, type_info = line.partition(":")
                 return type_info.strip()
     except OSError:
         # 'oscap info' exitted with a non-zero exit code -> unknown doc
         # type
         return None
Example #11
0
    def exec_readlines_test_normal_output(self):
        """Test the output of execReadlines."""

        # Test regular-looking output
        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write(
                """#!/bin/sh
echo "one"
echo "two"
echo "three"
exit 0
"""
            )
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(StopIteration, rl_iterator.__next__)

        # Test output with no end of line
        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write(
                """#!/bin/sh
echo "one"
echo "two"
echo -n "three"
exit 0
"""
            )
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(StopIteration, rl_iterator.__next__)
Example #12
0
def journalctl_callback():
    """Callback to get logs from journalctl."""

    # regex to filter log messages from anaconda's process (we have that in our
    # logs)
    anaconda_log_line = re.compile(r"\[%d\]:" % os.getpid())
    ret = ""
    for line in iutil.execReadlines("journalctl", ["-b"]):
        if anaconda_log_line.search(line) is None:
            # not an anaconda's message
            ret += line + "\n"

    return ret
Example #13
0
def journalctl_callback():
    """Callback to get logs from journalctl."""

    # regex to filter log messages from anaconda's process (we have that in our
    # logs)
    anaconda_log_line = re.compile(r"\[%d\]:" % os.getpid())
    ret = ""
    for line in iutil.execReadlines("journalctl", ["-b"]):
        if anaconda_log_line.search(line) is None:
            # not an anaconda's message
            ret += line + "\n"

    return ret
Example #14
0
    def resolve_date_format_test(self):
        """All locales' date formats should be properly resolved."""

        locales = (line.strip() for line in execReadlines("locale", ["-a"]))
        for locale in locales:
            try:
                locale_mod.setlocale(locale_mod.LC_ALL, locale)
            except locale_mod.Error:
                # cannot set locale (a bug in the locale module?)
                continue

            order = localization.resolve_date_format(1, 2, 3, fail_safe=False)[0]
            for i in (1, 2, 3):
                self.assertIn(i, order)
Example #15
0
    def exec_readlines_test_normal_output(self):
        """Test the output of execReadlines."""

        # Test regular-looking output
        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo "three"
exit 0
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(StopIteration, rl_iterator.__next__)

        # Test output with no end of line
        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo -n "three"
exit 0
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(StopIteration, rl_iterator.__next__)
Example #16
0
def run_grubby(args=None):
    """ Run grubby and retrieve the kernel, initrd and boot arguments

        :param list args: Arguments to pass to grubby.
        :returns: kernel path, initrd path, root device, kernel cmdline args.
        :rtype: namedtuple
        :raises: some error on failure

        The returned namedtuple contains the following attributes:
            kernel, initrd, root, args
    """
    boot_info = _BootInfo()
    attrs = list(_BootInfo._fields)

    if not args:
        args = ["--info", "DEFAULT"]

    # Run grubby and fill in the boot_info with the first values seen, exit the
    # loop when all of the needed values have been gathered.
    try:

        for line in execReadlines("grubby", args, root=getSysroot()):
            key, _sep, value = line.partition("=")
            value = unquote(value)
            if key in attrs:
                setattr(boot_info, key, value)
                attrs.remove(key)
            if not attrs:
                break
    except OSError as e:
        log.error("run_grubby failed: %s", e)
        raise GrubbyInfoError(e)

    if len(attrs) > 0:
        raise GrubbyInfoError("Missing values: %s" % ", ".join(attrs))

    log.info("grubby boot info for (%s): %s", args, boot_info)
    return boot_info
Example #17
0
def run_grubby(args=None):
    """ Run grubby and retrieve the kernel, initrd and boot arguments

        :param list args: Arguments to pass to grubby.
        :returns: kernel path, initrd path, root device, kernel cmdline args.
        :rtype: namedtuple
        :raises: some error on failure

        The returned namedtuple contains the following attributes:
            kernel, initrd, root, args
    """
    boot_info = _BootInfo()
    attrs = list(_BootInfo._fields)

    if not args:
        args = ["--info", "DEFAULT"]

    # Run grubby and fill in the boot_info with the first values seen, exit the
    # loop when all of the needed values have been gathered.
    try:

        for line in execReadlines("grubby", args, root=getSysroot()):
            key, _sep, value = line.partition("=")
            value = unquote(value)
            if key in attrs:
                setattr(boot_info, key, value)
                attrs.remove(key)
            if not attrs:
                break
    except OSError as e:
        log.error("run_grubby failed: %s", e)
        raise GrubbyInfoError(e)

    if len(attrs) > 0:
        raise GrubbyInfoError("Missing values: %s" % ", ".join(attrs))

    log.info("grubby boot info for (%s): %s", args, boot_info)
    return boot_info
Example #18
0
 def execParseKickstart(self, ks_file):
     return list(iutil.execReadlines(self.command, ["--tmpdir", self.tmpdir, ks_file]))
 def execParseKickstart(self, ks_file):
     return list(iutil.execReadlines(self.command, ["--tmpdir", self.tmpdir, ks_file], filter_stderr=True))
 def get_doc_type(file_path):
     for line in execReadlines("oscap", ["info", file_path]):
         if line.startswith("Document type:"):
             _prefix, _sep, type_info = line.partition(":")
             return type_info.strip()
Example #21
0
    def exec_readlines_test_exits(self):
        """Test execReadlines in different child exit situations."""

        # Tests that exit on signal will raise OSError once output
        # has been consumed, otherwise the test will exit normally.

        # Test a normal, non-0 exit
        with tempfile.NamedTemporaryFile() as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo "three"
exit 1
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(rl_iterator.next(), "one")
                self.assertEqual(rl_iterator.next(), "two")
                self.assertEqual(rl_iterator.next(), "three")
                self.assertRaises(OSError, rl_iterator.next)

        # Test exit on signal
        with tempfile.NamedTemporaryFile() as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo "three"
kill -TERM $$
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(rl_iterator.next(), "one")
                self.assertEqual(rl_iterator.next(), "two")
                self.assertEqual(rl_iterator.next(), "three")
                self.assertRaises(OSError, rl_iterator.next)

        # Repeat the above two tests, but exit before a final newline
        with tempfile.NamedTemporaryFile() as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo -n "three"
exit 1
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(rl_iterator.next(), "one")
                self.assertEqual(rl_iterator.next(), "two")
                self.assertEqual(rl_iterator.next(), "three")
                self.assertRaises(OSError, rl_iterator.next)

        with tempfile.NamedTemporaryFile() as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo -n "three"
kill -TERM $$
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(rl_iterator.next(), "one")
                self.assertEqual(rl_iterator.next(), "two")
                self.assertEqual(rl_iterator.next(), "three")
                self.assertRaises(OSError, rl_iterator.next)
Example #22
0
 def get_doc_type(file_path):
     for line in execReadlines("oscap", ["info", file_path]):
         if line.startswith("Document type:"):
             _prefix, _sep, type_info = line.partition(":")
             return type_info.strip()
Example #23
0
    def exec_readlines_test_exits(self):
        """Test execReadlines in different child exit situations."""

        # Tests that exit on signal will raise OSError once output
        # has been consumed, otherwise the test will exit normally.

        # Test a normal, non-0 exit
        with tempfile.NamedTemporaryFile(mode="wt") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo "three"
exit 1
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(OSError, rl_iterator.__next__)

        # Test exit on signal
        with tempfile.NamedTemporaryFile(mode="wt") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo "three"
kill -TERM $$
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(OSError, rl_iterator.__next__)

        # Repeat the above two tests, but exit before a final newline
        with tempfile.NamedTemporaryFile(mode="wt") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo -n "three"
exit 1
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(OSError, rl_iterator.__next__)

        with tempfile.NamedTemporaryFile(mode="wt") as testscript:
            testscript.write("""#!/bin/sh
echo "one"
echo "two"
echo -n "three"
kill -TERM $$
""")
            testscript.flush()

            with timer(5):
                rl_iterator = iutil.execReadlines("/bin/sh", [testscript.name])
                self.assertEqual(next(rl_iterator), "one")
                self.assertEqual(next(rl_iterator), "two")
                self.assertEqual(next(rl_iterator), "three")
                self.assertRaises(OSError, rl_iterator.__next__)