python类ndiff()的实例源码

test_dis.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def do_disassembly_test(self, func, expected):
        s = StringIO.StringIO()
        save_stdout = sys.stdout
        sys.stdout = s
        dis.dis(func)
        sys.stdout = save_stdout
        got = s.getvalue()
        # Trim trailing blanks (if any).
        lines = got.split('\n')
        lines = [line.rstrip() for line in lines]
        expected = expected.split("\n")
        import difflib
        if expected != lines:
            self.fail(
                "events did not match expectation:\n" +
                "\n".join(difflib.ndiff(expected,
                                        lines)))
testcases.py 文件源码 项目:liberator 作者: libscie 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def assertHTMLEqual(self, html1, html2, msg=None):
        """
        Asserts that two HTML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid HTML.
        """
        dom1 = assert_and_parse_html(self, html1, msg, 'First argument is not valid HTML:')
        dom2 = assert_and_parse_html(self, html2, msg, 'Second argument is not valid HTML:')

        if dom1 != dom2:
            standardMsg = '%s != %s' % (
                safe_repr(dom1, True), safe_repr(dom2, True))
            diff = ('\n' + '\n'.join(difflib.ndiff(
                six.text_type(dom1).splitlines(),
                six.text_type(dom2).splitlines(),
            )))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
testcases.py 文件源码 项目:liberator 作者: libscie 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def assertXMLEqual(self, xml1, xml2, msg=None):
        """
        Asserts that two XML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid XML.
        """
        try:
            result = compare_xml(xml1, xml2)
        except Exception as e:
            standardMsg = 'First or second argument is not valid XML\n%s' % e
            self.fail(self._formatMessage(msg, standardMsg))
        else:
            if not result:
                standardMsg = '%s != %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
                diff = ('\n' + '\n'.join(
                    difflib.ndiff(
                        six.text_type(xml1).splitlines(),
                        six.text_type(xml2).splitlines(),
                    )
                ))
                standardMsg = self._truncateMessage(standardMsg, diff)
                self.fail(self._formatMessage(msg, standardMsg))
testcases.py 文件源码 项目:djanoDoc 作者: JustinChavez 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def assertHTMLEqual(self, html1, html2, msg=None):
        """
        Asserts that two HTML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid HTML.
        """
        dom1 = assert_and_parse_html(self, html1, msg,
            'First argument is not valid HTML:')
        dom2 = assert_and_parse_html(self, html2, msg,
            'Second argument is not valid HTML:')

        if dom1 != dom2:
            standardMsg = '%s != %s' % (
                safe_repr(dom1, True), safe_repr(dom2, True))
            diff = ('\n' + '\n'.join(difflib.ndiff(
                           six.text_type(dom1).splitlines(),
                           six.text_type(dom2).splitlines())))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
testcases.py 文件源码 项目:djanoDoc 作者: JustinChavez 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def assertXMLEqual(self, xml1, xml2, msg=None):
        """
        Asserts that two XML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid XML.
        """
        try:
            result = compare_xml(xml1, xml2)
        except Exception as e:
            standardMsg = 'First or second argument is not valid XML\n%s' % e
            self.fail(self._formatMessage(msg, standardMsg))
        else:
            if not result:
                standardMsg = '%s != %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
                diff = ('\n' + '\n'.join(
                    difflib.ndiff(
                        six.text_type(xml1).splitlines(),
                        six.text_type(xml2).splitlines(),
                    )
                ))
                standardMsg = self._truncateMessage(standardMsg, diff)
                self.fail(self._formatMessage(msg, standardMsg))
comparators.py 文件源码 项目:webmon 作者: KarolBedkowski 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def compare(self, old: str, old_date: str, new: str, new_date: str,
                ctx: common.Context, meta: dict) \
            -> ty.Tuple[bool, ty.Optional[str], ty.Optional[dict]]:
        # pylint: disable=invalid-sequence-index
        old = old.replace(common.RECORD_SEPARATOR, '\n\n')
        new = new.replace(common.RECORD_SEPARATOR, '\n\n')
        old_lines = old.split('\n')
        res = list(difflib.ndiff(old_lines, new.split('\n')))

        changed_lines = sum(1 for line in res if line and line[0] != ' ')
        if not _check_changes(ctx, changed_lines, len(old_lines),
                              self.conf.get("changes_threshold"),
                              self.conf.get("min_changed")):
            return False, None, None

        return True, "\n".join(res), self.opts
case.py 文件源码 项目:empyrion-python-api 作者: huhlig 项目源码 文件源码 阅读 95 收藏 0 点赞 0 评论 0
def assertMultiLineEqual(self, first, second, msg=None):
        """Assert that two multi-line strings are equal."""
        self.assertIsInstance(first, basestring,
                'First argument is not a string')
        self.assertIsInstance(second, basestring,
                'Second argument is not a string')

        if first != second:
            # don't use difflib if the strings are too long
            if (len(first) > self._diffThreshold or
                len(second) > self._diffThreshold):
                self._baseAssertEqual(first, second, msg)
            firstlines = first.splitlines(True)
            secondlines = second.splitlines(True)
            if len(firstlines) == 1 and first.strip('\r\n') == first:
                firstlines = [first + '\n']
                secondlines = [second + '\n']
            standardMsg = '%s != %s' % (safe_repr(first, True),
                                        safe_repr(second, True))
            diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
malware_config.py 文件源码 项目:fame_modules 作者: certsocietegenerale 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def add_to_results(self, block, last=None):
        b = {
            '_id': block['_id'],
            'created': block['created'],
            'action': block['action'],
            'type': block['type'],
            'botnet': block['botnet'],
            'target': block['target'],
            'monitor': block['monitor'],
            'content': block['content']
        }

        if block['action'] == ACTION_UPDATE:
            b['diff'] = ''.join(ndiff(last['content'].splitlines(1), block['content'].splitlines(1)))

        self.results.append(b)
actions.py 文件源码 项目:ci_edit 作者: google 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def applyDocumentUpdate(self, data):
    diff = difflib.ndiff(self.lines, self.doDataToLines(data))
    ndiff = []
    counter = 0
    for i in diff:
      if i[0] != ' ':
        if counter:
          ndiff.append(counter)
          counter = 0
        if i[0] in ['+', '-']:
          ndiff.append(i)
      else:
        counter += 1
    if counter:
      ndiff.append(counter)
    if len(ndiff) == 1 and type(ndiff[0]) is type(0):
      # Nothing was changed. The only entry is a 'skip these lines'
      self.setMessage('No matches found')
      return
    ndiff = tuple(ndiff)
    if 0:
      for i in ndiff:
        app.log.info(i)
    self.redoAddChange(('ld', ndiff))
    self.redo()
case.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def assertMultiLineEqual(self, first, second, msg=None):
        """Assert that two multi-line strings are equal."""
        self.assertIsInstance(first, str, 'First argument is not a string')
        self.assertIsInstance(second, str, 'Second argument is not a string')

        if first != second:
            # don't use difflib if the strings are too long
            if (len(first) > self._diffThreshold or
                len(second) > self._diffThreshold):
                self._baseAssertEqual(first, second, msg)
            firstlines = first.splitlines(keepends=True)
            secondlines = second.splitlines(keepends=True)
            if len(firstlines) == 1 and first.strip('\r\n') == first:
                firstlines = [first + '\n']
                secondlines = [second + '\n']
            standardMsg = '%s != %s' % _common_shorten_repr(first, second)
            diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
test_dis27.py 文件源码 项目:python-xdis 作者: rocky 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def do_disassembly_test(self, func, expected):
            s = StringIO()
            save_stdout = sys.stdout
            sys.stdout = s
            dis.dis(func)
            sys.stdout = save_stdout
            got = s.getvalue()
            # Trim trailing blanks (if any).
            lines = got.split('\n')
            # lines = [line.rstrip() for line in lines]
            expected = expected.split("\n")
            import difflib
            if expected != lines:
                self.fail(
                    "events did not match expectation:\n" +
                    "\n".join(difflib.ndiff(expected,
                                            lines)))
test_dis.py 文件源码 项目:python-xdis 作者: rocky 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def do_disassembly(self, func, expected):

        co = func.__code__
        bytecode = Bytecode(co, opc)
        got = bytecode.dis()

        # Trim trailing blanks (if any).
        lines = got.split('\n')
        lines = [line.rstrip() for line in lines]
        expected = expected.split("\n")
        import difflib
        if expected != lines:
            self.fail(
                "events did not match expectation:\n" +
                "\n".join(difflib.ndiff(expected,
                                        lines)))
util.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _compare_eq_iterable(left, right, verbose=False):
    if not verbose:
        return [u('Use -v to get the full diff')]
    # dynamic import to speedup pytest
    import difflib

    try:
        left_formatting = pprint.pformat(left).splitlines()
        right_formatting = pprint.pformat(right).splitlines()
        explanation = [u('Full diff:')]
    except Exception:
        # hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling
        # sorted() on a list would raise. See issue #718.
        # As a workaround, the full diff is generated by using the repr() string of each item of each container.
        left_formatting = sorted(repr(x) for x in left)
        right_formatting = sorted(repr(x) for x in right)
        explanation = [u('Full diff (fallback to calling repr on each item):')]
    explanation.extend(line.strip() for line in difflib.ndiff(left_formatting, right_formatting))
    return explanation
conda_manager.py 文件源码 项目:anaconda-project 作者: Anaconda-Platform 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _pretty_diff(old_list, new_list, indent):
    diff = list(difflib.ndiff(old_list, new_list))

    # the diff has - lines, + lines, and ? lines
    # the ? lines have the ^ pointing to changed character,
    # which is just noise for these short version strings.
    # the diff also has lines with just whitespace at the
    # front, which are context.

    # remove context lines
    diff = filter(lambda x: x[0] != ' ', diff)
    # remove ? lines
    diff = filter(lambda x: x[0] != '?', diff)

    def indent_more(s):
        if s.startswith("+ "):
            return "+ " + indent + s[2:]
        elif s.startswith("- "):
            return "- " + indent + s[2:]
        else:
            return s  # pragma: no cover # should not be any other kind of lines

    diff = map(indent_more, diff)

    return list(diff)
testcases.py 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def assertHTMLEqual(self, html1, html2, msg=None):
        """
        Asserts that two HTML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid HTML.
        """
        dom1 = assert_and_parse_html(self, html1, msg,
            'First argument is not valid HTML:')
        dom2 = assert_and_parse_html(self, html2, msg,
            'Second argument is not valid HTML:')

        if dom1 != dom2:
            standardMsg = '%s != %s' % (
                safe_repr(dom1, True), safe_repr(dom2, True))
            diff = ('\n' + '\n'.join(difflib.ndiff(
                           six.text_type(dom1).splitlines(),
                           six.text_type(dom2).splitlines())))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
testcases.py 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def assertXMLEqual(self, xml1, xml2, msg=None):
        """
        Asserts that two XML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid XML.
        """
        try:
            result = compare_xml(xml1, xml2)
        except Exception as e:
            standardMsg = 'First or second argument is not valid XML\n%s' % e
            self.fail(self._formatMessage(msg, standardMsg))
        else:
            if not result:
                standardMsg = '%s != %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
                diff = ('\n' + '\n'.join(
                    difflib.ndiff(
                        six.text_type(xml1).splitlines(),
                        six.text_type(xml2).splitlines(),
                    )
                ))
                standardMsg = self._truncateMessage(standardMsg, diff)
                self.fail(self._formatMessage(msg, standardMsg))
universe_builder.py 文件源码 项目:dcos-rabbitmq 作者: sheepkiller 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _apply_templating_to_file(self, filename, orig_content):
        rabbitmq_mapping = self._get_rabbitmq_mapping_for_content(orig_content)
        new_content = orig_content
        for rabbitmq_key, rabbitmq_val in rabbitmq_mapping.items():
            new_content = new_content.replace('{{%s}}' % rabbitmq_key, rabbitmq_val)
        if orig_content == new_content:
            logger.info('')
            logger.info('No templating detected in {}, leaving file as-is'.format(filename))
            return orig_content
        logger.info('')
        logger.info('Applied templating changes to {}:'.format(filename))
        logger.info('Template params used:')
        rabbitmq_keys = list(rabbitmq_mapping.keys())
        rabbitmq_keys.sort()
        for key in rabbitmq_keys:
            logger.info('  {{%s}} => %s' % (key, rabbitmq_mapping[key]))
        logger.info('Resulting diff:')
        logger.info('\n'.join(difflib.ndiff(orig_content.split('\n'), new_content.split('\n'))))
        return new_content
testcases.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def assertHTMLEqual(self, html1, html2, msg=None):
        """
        Asserts that two HTML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid HTML.
        """
        dom1 = assert_and_parse_html(self, html1, msg,
            'First argument is not valid HTML:')
        dom2 = assert_and_parse_html(self, html2, msg,
            'Second argument is not valid HTML:')

        if dom1 != dom2:
            standardMsg = '%s != %s' % (
                safe_repr(dom1, True), safe_repr(dom2, True))
            diff = ('\n' + '\n'.join(difflib.ndiff(
                           six.text_type(dom1).splitlines(),
                           six.text_type(dom2).splitlines())))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
case.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def assertDictEqual(self, d1, d2, msg=None):
        self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
        self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')

        if d1 != d2:
            standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
            diff = ('\n' + '\n'.join(difflib.ndiff(
                           pprint.pformat(d1).splitlines(),
                           pprint.pformat(d2).splitlines())))
            standardMsg = self._truncateMessage(standardMsg, diff)
            self.fail(self._formatMessage(msg, standardMsg))
test_email_renamed.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def ndiffAssertEqual(self, first, second):
        """Like failUnlessEqual except use ndiff for readable output."""
        if first <> second:
            sfirst = str(first)
            ssecond = str(second)
            diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
            fp = StringIO()
            print >> fp, NL, NL.join(diff)
            raise self.failureException, fp.getvalue()


问题


面经


文章

微信
公众号

扫码关注公众号