本文整理汇总了Python中difflib.unified_diff方法的典型用法代码示例。如果您正苦于以下问题:Python difflib.unified_diff方法的具体用法?Python difflib.unified_diff怎么用?Python difflib.unified_diff使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类difflib
的用法示例。
在下文中一共展示了difflib.unified_diff方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_bootstrap_copy
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def test_bootstrap_copy(self):
wf = OBSLocal.StagingWorkflow()
fc = FreezeCommand(wf.api)
fp = self._get_fixture_path('staging-meta-for-bootstrap-copy.xml')
fixture = subprocess.check_output('/usr/bin/xmllint --format %s' % fp, shell=True).decode('utf-8')
f = tempfile.NamedTemporaryFile(delete=False)
f.write(fc.prj_meta_for_bootstrap_copy('openSUSE:Factory:Staging:A'))
f.close()
output = subprocess.check_output('/usr/bin/xmllint --format %s' % f.name, shell=True).decode('utf-8')
for line in difflib.unified_diff(fixture.split("\n"), output.split("\n")):
print(line)
self.assertEqual(output, fixture)
示例2: _assertSchemaEqual
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def _assertSchemaEqual(expected, actual, testcase):
"""Utility method to dump diffs if the schema aren't equal.
Args:
expected: object, the expected results.
actual: object, the actual results.
testcase: unittest.TestCase, the test case this assertion is used within.
"""
if expected != actual:
expected_text = json.dumps(expected, indent=2, sort_keys=True)
actual_text = json.dumps(actual, indent=2, sort_keys=True)
diff = difflib.unified_diff(expected_text.splitlines(True),
actual_text.splitlines(True),
fromfile='expected.schema',
tofile='actual.schema')
diff_text = ''.join(list(diff))
testcase.fail('Schema differs from expected:\n%s' % diff_text)
示例3: get_diff_text
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def get_diff_text(old, new, filename):
"""Return text of unified diff between old and new."""
newline = '\n'
diff = difflib.unified_diff(
old, new,
'original/' + filename,
'fixed/' + filename,
lineterm=newline)
text = ''
for line in diff:
text += line
# Work around missing newline (http://bugs.python.org/issue2142).
if text and not line.endswith(newline):
text += newline + r'\ No newline at end of file' + newline
return text
示例4: _cache_tlds
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def _cache_tlds(self, tlds):
'''Logs a diff of the new TLDs and caches them on disk, according to
settings passed to __init__.'''
if LOG.isEnabledFor(logging.DEBUG):
import difflib
snapshot_stream = pkg_resources.resource_stream(__name__, '.tld_set_snapshot')
with closing(snapshot_stream) as snapshot_file:
snapshot = sorted(
json.loads(snapshot_file.read().decode('utf-8'))
)
new = sorted(tlds)
LOG.debug('computed TLD diff:\n' + '\n'.join(difflib.unified_diff(
snapshot,
new,
fromfile=".tld_set_snapshot",
tofile=self.cache_file
)))
if self.cache_file:
try:
with open(self.cache_file, 'w') as cache_file:
json.dump(tlds, cache_file)
except IOError as ioe:
LOG.warn("unable to cache TLDs in file %s: %s", self.cache_file, ioe)
示例5: get_correct_indentation_diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def get_correct_indentation_diff(code, filename):
"""
Generate a diff to make code correctly indented.
:param code: a string containing a file's worth of Python code
:param filename: the filename being considered (used in diff generation only)
:returns: a unified diff to make code correctly indented, or
None if code is already correctedly indented
"""
code_buffer = StringIO(code)
output_buffer = StringIO()
reindenter = reindent.Reindenter(code_buffer)
reindenter.run()
reindenter.write(output_buffer)
reindent_output = output_buffer.getvalue()
output_buffer.close()
if code != reindent_output:
diff_generator = difflib.unified_diff(code.splitlines(True), reindent_output.splitlines(True),
fromfile=filename, tofile=filename + " (reindented)")
# work around http://bugs.python.org/issue2142
diff_tuple = map(clean_diff_line_for_python_bug_2142, diff_generator)
diff = "".join(diff_tuple)
return diff
else:
return None
示例6: assertLinesEqual
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def assertLinesEqual(self, expected, actual, message):
if actual != expected:
if len(actual) < len(expected):
sys.stderr.write(
dedent(
"""\
WARNING: the actual text is shorter that the expected text.
Some information may be LOST!
"""
)
)
for line in difflib.unified_diff(
expected, actual, fromfile="<expected>", tofile="<actual>"
):
if not line.endswith("\n"):
line += "\n"
sys.stderr.write(line)
self.fail(message)
示例7: test_05_package_to_api2
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def test_05_package_to_api2(self):
context = {"model": model,
"session": model.Session}
pkg = model.Session.query(model.Package).filter_by(name='annakarenina').first()
as_dict = pkg.as_dict(ref_package_by='id', ref_group_by='id')
dictize = package_to_api2(pkg, context)
as_dict_string = pformat(as_dict)
dictize_string = pformat(dictize)
print as_dict_string
print dictize_string
assert package_to_api2(pkg, context) == dictize, "\n".join(unified_diff(as_dict_string.split("\n"), dictize_string.split("\n")))
示例8: test_06_package_to_api2_with_relationship
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def test_06_package_to_api2_with_relationship(self):
context = {"model": model,
"session": model.Session}
pkg = model.Session.query(model.Package).filter_by(name='homer').one()
as_dict = pkg.as_dict(ref_package_by='id', ref_group_by='id')
as_dict['license_title'] = None
as_dict['num_tags'] = 0
as_dict['num_resources'] = 0
dictize = package_to_api2(pkg, context)
as_dict["relationships"].sort(key=lambda x:x.items())
dictize["relationships"].sort(key=lambda x:x.items())
# the is_dict method doesn't care about organizations
del dictize['organization']
as_dict_string = pformat(as_dict)
dictize_string = pformat(dictize)
print as_dict_string
print dictize_string
assert as_dict == dictize, "\n".join(unified_diff(as_dict_string.split("\n"), dictize_string.split("\n")))
示例9: diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def diff(string_a, string_b):
"""Return unified diff of strings."""
string_a = string_a.splitlines(1)
string_b = string_b.splitlines(1)
result = difflib.unified_diff(string_a, string_b)
return ''.join(result)
示例10: compareFiles
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def compareFiles(file1,file2):
diff = difflib.unified_diff(
file1.readlines(),
file2.readlines(),
fromfile='saveFile.txt',
tofile='restoreFile.txt',
)
numDifferences = 0
for line in diff:
numDifferences = numDifferences+1
sys.stdout.write(line)
if (numDifferences>0):
print("Error:", numDifferences, " lines are different between files.")
else:
print("OK, files are identical")
示例11: compareFiles
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def compareFiles(self, file1,file2):
diff = difflib.unified_diff(
file1.readlines(),
file2.readlines(),
fromfile='saveFile.txt',
tofile='restoreFile.txt',
)
numDifferences = 0
for line in diff:
numDifferences = numDifferences+1
sys.stdout.write(line)
self.assertEqual(numDifferences,0)
示例12: __init__
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def __init__(self, old, new):
self.old = old
self.new = new
diff = unified_diff(
old.splitlines(),
new.splitlines(),
fromfile='test.py',
tofile='test.py',
)
self._diff = diff
示例13: diff_files
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def diff_files():
"""
diff
"""
with open('old.md', 'r') as old, open('README.md', 'r') as new:
diff = difflib.unified_diff(old.readlines(), new.readlines(), fromfile='old', tofile='new')
changes = []
for line in diff:
if line.startswith('+'):
changes.append(str(line))
new = ''.join(changes[2:]).replace("+", "")
with open('changes', 'w') as out:
out.write(new)
示例14: diff_texts
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
lineterm="")
示例15: diff_texts
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import unified_diff [as 别名]
def diff_texts(a, b, filename):
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(reserialized)",
lineterm="")