Unit test for content diff

merge-requests/30/head
Bob Mottram 2022-04-10 20:19:40 +01:00
parent bd05fdb51b
commit e286cf8661
2 changed files with 65 additions and 0 deletions

View File

@ -7,6 +7,7 @@ __email__ = "bob@libreserver.org"
__status__ = "Production"
__module_group__ = "Core"
import difflib
import math
import html
import os
@ -1415,3 +1416,52 @@ def import_emoji(base_dir: str, import_filename: str, session) -> None:
added += 1
save_json(emoji_dict, base_dir + '/emoji/default_emoji.json')
print(str(added) + ' custom emoji added')
def content_diff(content: str, prev_content: str) -> str:
"""Returns a diff for the given content
"""
d = difflib.Differ()
text1_lines = content.splitlines()
text2_lines = prev_content.splitlines()
diff = d.compare(text1_lines, text2_lines)
diff_content = content
diff_text = ''
reference_text = ''
change_positions = ''
for line in diff:
if line.startswith('- '):
reference_text = line[2:]
elif line.startswith('? '):
change_positions = line[2:]
state = 0
ctr = 0
for changed_char in change_positions:
if state == 0:
if changed_char == '-':
diff_text += \
'<label class="diff_add">' + reference_text[ctr]
ctr += 1
state = 1
continue
elif changed_char == '+':
diff_text += \
'<label class="diff_remove">' + reference_text[ctr]
ctr += 1
state = 1
continue
elif state == 1:
if changed_char != '-' and changed_char != '+':
diff_text += '</label>' + reference_text[ctr]
ctr += 1
state = 0
continue
diff_text += reference_text[ctr]
ctr += 1
while ctr < len(reference_text):
diff_text += reference_text[ctr]
ctr += 1
diff_content = diff_content.replace(reference_text, diff_text)
return diff_content

View File

@ -129,6 +129,7 @@ from inbox import json_post_allows_comments
from inbox import valid_inbox
from inbox import valid_inbox_filenames
from categories import guess_hashtag_category
from content import content_diff
from content import bold_reading_string
from content import safe_web_text
from content import words_similarity
@ -6917,6 +6918,19 @@ def _test_bold_reading() -> None:
assert text_bold == expected
def _test_diff_content() -> None:
print('diff_content')
prev_content = \
'Some text before.\nThis is some content.\nThis is another line.'
content = \
'Some text before.\nThis is some more content.\nThis is another line.'
result = content_diff(content, prev_content)
expected = 'Some text before.\n' + \
'This is some <label class="diff_add">' + \
'more </label>content.\nThis is another line.'
assert result == expected
def run_all_tests():
base_dir = os.getcwd()
print('Running tests...')
@ -6934,6 +6948,7 @@ def run_all_tests():
_test_checkbox_names()
_test_thread_functions()
_test_functions()
_test_diff_content()
_test_bold_reading()
_test_published_to_local_timezone()
_test_safe_webtext()