def test_lint_test_files__errors(self):
        options = optparse.Values({
            'platform': 'test',
            'debug_rwt_logging': False
        })
        host = MockHost()

        # FIXME: incorrect complaints about spacing pylint: disable=C0322
        port = host.port_factory.get(options.platform, options=options)
        port.expectations_dict = lambda: {
            'foo': '-- syntax error1',
            'bar': '-- syntax error2'
        }

        host.port_factory.get = lambda platform, options=None: port
        host.port_factory.all_port_names = lambda platform=None: [port.name()]

        logging_stream = StringIO()

        res = lint_test_expectations.lint(host, options, logging_stream)

        self.assertEqual(res, -1)
        self.assertIn('Lint failed', logging_stream.getvalue())
        self.assertIn('foo:1', logging_stream.getvalue())
        self.assertIn('bar:1', logging_stream.getvalue())
Example #2
0
    def test_simple_tee(self):
        file1, file2 = StringIO(), StringIO()
        tee = Tee(file1, file2)
        tee.write("foo bar\n")
        tee.write("baz\n")

        self.assertEqual(file1.getvalue(), "foo bar\nbaz\n")
        self.assertEqual(file2.getvalue(), file1.getvalue())
Example #3
0
class SkipTest(unittest.TestCase):
    def setUp(self):
        self.logger = logging.getLogger(__name__)

        self.old_level = self.logger.level
        self.logger.setLevel(logging.INFO)

        self.old_propagate = self.logger.propagate
        self.logger.propagate = False

        self.log_stream = StringIO()
        self.handler = logging.StreamHandler(self.log_stream)
        self.logger.addHandler(self.handler)

        self.foo_was_called = False

    def tearDown(self):
        self.logger.removeHandler(self.handler)
        self.propagate = self.old_propagate
        self.logger.setLevel(self.old_level)

    def create_fixture_class(self):
        class TestSkipFixture(object):
            def __init__(self, callback):
                self.callback = callback

            def test_foo(self):
                self.callback()

        return TestSkipFixture

    def foo_callback(self):
        self.foo_was_called = True

    def test_skip_if_false(self):
        klass = skip_if(self.create_fixture_class(),
                        False,
                        'Should not see this message.',
                        logger=self.logger)
        klass(self.foo_callback).test_foo()
        self.assertEqual(self.log_stream.getvalue(), '')
        self.assertTrue(self.foo_was_called)

    def test_skip_if_true(self):
        klass = skip_if(self.create_fixture_class(),
                        True,
                        'Should see this message.',
                        logger=self.logger)
        klass(self.foo_callback).test_foo()
        self.assertEqual(
            self.log_stream.getvalue(),
            'Skipping webkitpy.test.skip_unittest.TestSkipFixture: Should see this message.\n'
        )
        self.assertFalse(self.foo_was_called)
Example #4
0
 def set_reviewer(self, reviewer):
     latest_entry = self.latest_entry()
     latest_entry_contents = latest_entry.contents()
     reviewer_text = latest_entry.reviewer()
     found_nobody = re.search("NOBODY\s*\(OOPS!\)", latest_entry_contents,
                              re.MULTILINE)
     found_reviewer_or_unreviewed = latest_entry.has_valid_reviewer()
     if not found_nobody and not found_reviewer_or_unreviewed and not reviewer_text:
         bug_url_number_of_items = len(
             re.findall(config_urls.bug_url_long, latest_entry_contents,
                        re.MULTILINE))
         bug_url_number_of_items += len(
             re.findall(config_urls.bug_url_short, latest_entry_contents,
                        re.MULTILINE))
         result = StringIO()
         with self._filesystem.open_text_file_for_reading(
                 self.path) as file:
             for line in file:
                 found_bug_url = re.search(config_urls.bug_url_long, line)
                 if not found_bug_url:
                     found_bug_url = re.search(config_urls.bug_url_short,
                                               line)
                 result.write(line)
                 if found_bug_url:
                     if bug_url_number_of_items == 1:
                         result.write("\n        Reviewed by %s.\n" %
                                      reviewer)
                     bug_url_number_of_items -= 1
         self._filesystem.write_text_file(self.path, result.getvalue())
     else:
         data = self._filesystem.read_text_file(self.path)
         newdata = data.replace("NOBODY (OOPS!)", reviewer)
         self._filesystem.write_text_file(self.path, newdata)
Example #5
0
class _CaptureAndPassThroughStream(object):
    def __init__(self, stream):
        self._buffer = StringIO()
        self._stream = stream

    def write(self, msg):
        self._stream.write(msg)

        # Note that we don't want to capture any output generated by the debugger
        # because that could cause the results of capture_output() to be invalid.
        if not self._message_is_from_pdb():
            self._buffer.write(msg)

    def _message_is_from_pdb(self):
        # We will assume that if the pdb module is in the stack then the output
        # is being generated by the python debugger (or the user calling something
        # from inside the debugger).
        import inspect
        import pdb
        stack = inspect.stack()
        return any(frame[1] == pdb.__file__.replace('.pyc', '.py')
                   for frame in stack)

    def flush(self):
        self._stream.flush()

    def getvalue(self):
        return self._buffer.getvalue()
    def test_lint_test_files(self):
        logging_stream = StringIO()
        options = optparse.Values({'platform': 'test-mac-leopard'})
        host = MockHost()

        # pylint appears to complain incorrectly about the method overrides pylint: disable=E0202,C0322
        # FIXME: incorrect complaints about spacing pylint: disable=C0322
        host.port_factory.all_port_names = lambda platform=None: [platform]

        res = lint_test_expectations.lint(host, options, logging_stream)

        self.assertEqual(res, 0)
        self.assertIn('Lint succeeded', logging_stream.getvalue())
Example #7
0
 def set_short_description_and_bug_url(self, short_description, bug_url):
     result = StringIO()
     with self._filesystem.open_text_file_for_reading(self.path) as file:
         short_description_placeholder = "Need a short description (OOPS!)."
         bug_url_placeholder = "Need the bug URL (OOPS!)."
         for line in file:
             stripped = line.strip()
             if stripped == short_description_placeholder:
                 line = self._changelog_indent + short_description + "\n"
             if stripped == bug_url_placeholder:
                 line = self._changelog_indent + bug_url + "\n"
             result.write(line)
     self._filesystem.write_text_file(self.path, result.getvalue())
Example #8
0
 def delete_entries(self, num_entries):
     date_line_regexp = re.compile(ChangeLogEntry.date_line_regexp)
     rolled_over_regexp = re.compile(ChangeLogEntry.rolled_over_regexp)
     entries = 0
     result = StringIO()
     with self._filesystem.open_text_file_for_reading(self.path) as file:
         for line in file:
             if date_line_regexp.match(line):
                 entries += 1
             elif rolled_over_regexp.match(line):
                 entries = num_entries + 1
             if entries > num_entries:
                 result.write(line)
     self._filesystem.write_text_file(self.path, result.getvalue())
Example #9
0
    def update_with_unreviewed_message(self, message):
        first_boilerplate_line_regexp = re.compile(
            "%sNeed a short description \(OOPS!\)\." % self._changelog_indent)
        removing_boilerplate = False
        result = StringIO()
        with self._filesystem.open_text_file_for_reading(self.path) as file:
            for line in file:
                if first_boilerplate_line_regexp.search(line):
                    message_lines = self._wrap_lines(message)
                    result.write(
                        first_boilerplate_line_regexp.sub(message_lines, line))
                    # Remove all the ChangeLog boilerplate, except the first line (date, name, e-mail).
                    removing_boilerplate = True
                elif removing_boilerplate:
                    if re.search(
                            "^[1-9]", line
                    ):  # each changelog entry is preceded by a date
                        removing_boilerplate = False

                if not removing_boilerplate:
                    result.write(line)
        self._filesystem.write_text_file(self.path, result.getvalue())
Example #10
0
    def test_no_tests_found(self):
        tester = Tester()
        errors = StringIO()

        # Here we need to remove any existing log handlers so that they
        # don't log the messages webkitpy.test while we're testing it.
        root_logger = logging.getLogger()
        root_handlers = root_logger.handlers
        root_logger.handlers = []

        tester.printer.stream = errors
        tester.finder.find_names = lambda args, run_all: []
        oc = OutputCapture()
        try:
            oc.capture_output()
            self.assertFalse(tester.run())
        finally:
            _, _, logs = oc.restore_output()
            root_logger.handlers = root_handlers

        self.assertIn('No tests to run', errors.getvalue())
        self.assertIn('No tests to run', logs)
 def test_logging_not_included(self):
     # This tests that if we don't hand a logger to the MeteredStream,
     # nothing is logged.
     logging_stream = StringIO()
     handler = logging.StreamHandler(logging_stream)
     root_logger = logging.getLogger()
     orig_level = root_logger.level
     root_logger.addHandler(handler)
     root_logger.setLevel(logging.DEBUG)
     try:
         self.meter = MeteredStream(self.stream,
                                    self.verbose,
                                    None,
                                    self.time_fn,
                                    8675,
                                    print_timestamps=self.print_timestamps)
         self.meter.write_throttled_update('foo')
         self.meter.write_update('bar')
         self.meter.write('baz')
         self.assertEqual(logging_stream.getvalue(), '')
     finally:
         root_logger.removeHandler(handler)
         root_logger.setLevel(orig_level)
Example #12
0
 def _log_exception(self):
     s = StringIO()
     traceback.print_exc(file=s)
     for l in s.getvalue().splitlines():
         _log.error('  ' + l.rstrip())
class RegularTest(unittest.TestCase):
    verbose = False
    isatty = False
    print_timestamps = None

    def setUp(self):
        self.stream = StringIO()
        self.stream.isatty = lambda: self.isatty

        # configure a logger to test that log calls do normally get included.
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        self.logger.propagate = False

        # add a dummy time counter for a default behavior.
        self.times = list(range(10))

        self.meter = MeteredStream(self.stream,
                                   self.verbose,
                                   self.logger,
                                   self.time_fn,
                                   8675,
                                   print_timestamps=self.print_timestamps)

    def tearDown(self):
        if self.meter:
            self.meter.cleanup()
            self.meter = None

    def time_fn(self):
        return self.times.pop(0)

    def test_logging_not_included(self):
        # This tests that if we don't hand a logger to the MeteredStream,
        # nothing is logged.
        logging_stream = StringIO()
        handler = logging.StreamHandler(logging_stream)
        root_logger = logging.getLogger()
        orig_level = root_logger.level
        root_logger.addHandler(handler)
        root_logger.setLevel(logging.DEBUG)
        try:
            self.meter = MeteredStream(self.stream,
                                       self.verbose,
                                       None,
                                       self.time_fn,
                                       8675,
                                       print_timestamps=self.print_timestamps)
            self.meter.write_throttled_update('foo')
            self.meter.write_update('bar')
            self.meter.write('baz')
            self.assertEqual(logging_stream.getvalue(), '')
        finally:
            root_logger.removeHandler(handler)
            root_logger.setLevel(orig_level)

    def _basic(self, times):
        self.times = times
        self.meter.write_update('foo')
        self.meter.write_update('bar')
        self.meter.write_throttled_update('baz')
        self.meter.write_throttled_update('baz 2')
        self.meter.writeln('done')
        self.assertEqual(self.times, [])
        return self.stream.getvalue()

    def test_basic(self):
        self.assertEqual(self._basic([0, 1, 2, 13, 14]),
                         'foo\nbar\nbaz 2\ndone\n')

    def _log_after_update(self):
        self.meter.write_update('foo')
        self.logger.info('bar')
        return self.stream.getvalue()

    def test_log_after_update(self):
        self.assertEqual(self._log_after_update(), 'foo\nbar\n')

    def test_log_args(self):
        self.logger.info('foo %s %d', 'bar', 2)
        self.assertEqual(self.stream.getvalue(), 'foo bar 2\n')

    def test_unicode(self):
        self.logger.info('‘example’')
        self.assertEqual(self.stream.getvalue()[-len('‘example’\n'):],
                         '‘example’\n')

        self.logger.info(u'\u2713')
        if sys.version_info > (3, 0):
            self.assertEqual(self.stream.getvalue()[-2:], u'\u2713\n')
        else:
            self.assertEqual(self.stream.buflist[-1][-2:], u'\u2713\n')

    def test_stream_with_encoding(self):
        class AsciiStream(StringIO):
            def write(self, s):
                return StringIO.write(self, '{}'.format(s))

        stream = AsciiStream()

        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)
        logger.propagate = False

        try:
            meter = MeteredStream(stream,
                                  self.verbose,
                                  logger,
                                  self.time_fn,
                                  8675,
                                  print_timestamps=self.print_timestamps)
            self.logger.info(u'\u2713')
            if sys.version_info > (3, 0):
                self.assertEqual(stream.getvalue()[-2:], '✓\n')
            else:
                self.assertEqual(stream.getvalue()[-2:], '?\n')
        finally:
            meter.cleanup()