// Copyright 2022 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT package gitdiff import ( "fmt" "html/template" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestDiffWithHighlight(t *testing.T) { t.Run("DiffLineAddDel", func(t *testing.T) { hcd := newHighlightCodeDiff() codeA := template.HTML(`x foo y`) codeB := template.HTML(`x bar y`) outDel := hcd.diffLineWithHighlight(DiffLineDel, codeA, codeB) assert.Equal(t, `x foo y`, string(outDel)) outAdd := hcd.diffLineWithHighlight(DiffLineAdd, codeA, codeB) assert.Equal(t, `x bar y`, string(outAdd)) }) t.Run("CleanUp", func(t *testing.T) { hcd := newHighlightCodeDiff() codeA := template.HTML(`this is updated comment`) outDel := hcd.diffLineWithHighlight(DiffLineDel, codeA, codeB) assert.Equal(t, `a comment`, string(outDel)) outAdd := hcd.diffLineWithHighlight(DiffLineAdd, codeA, codeB) assert.Equal(t, `updated comment`, string(outAdd)) }) t.Run("OpenCloseTags", func(t *testing.T) { hcd := newHighlightCodeDiff() hcd.placeholderTokenMap['O'], hcd.placeholderTokenMap['C'] = "", "" assert.Equal(t, "", string(hcd.recoverOneDiff("OC"))) assert.Equal(t, "", string(hcd.recoverOneDiff("O"))) assert.Equal(t, "", string(hcd.recoverOneDiff("C"))) }) } func TestDiffWithHighlightPlaceholder(t *testing.T) { hcd := newHighlightCodeDiff() output := hcd.diffLineWithHighlight(DiffLineDel, "a='\U00100000'", "a='\U0010FFFD''") assert.Equal(t, "", hcd.placeholderTokenMap[0x00100000]) assert.Equal(t, "", hcd.placeholderTokenMap[0x0010FFFD]) expected := fmt.Sprintf(`a='%s'`, "\U00100000") assert.Equal(t, expected, string(output)) hcd = newHighlightCodeDiff() output = hcd.diffLineWithHighlight(DiffLineAdd, "a='\U00100000'", "a='\U0010FFFD'") expected = fmt.Sprintf(`a='%s'`, "\U0010FFFD") assert.Equal(t, expected, string(output)) } func TestDiffWithHighlightPlaceholderExhausted(t *testing.T) { hcd := newHighlightCodeDiff() hcd.placeholderMaxCount = 0 placeHolderAmp := string(rune(0xFFFD)) output := hcd.diffLineWithHighlight(DiffLineDel, `<`, `>`) assert.Equal(t, placeHolderAmp+"lt;", string(output)) output = hcd.diffLineWithHighlight(DiffLineAdd, `<`, `>`) assert.Equal(t, placeHolderAmp+"gt;", string(output)) } func TestDiffWithHighlightTagMatch(t *testing.T) { f := func(t *testing.T, lineType DiffLineType) { totalOverflow := 0 for i := 0; ; i++ { hcd := newHighlightCodeDiff() hcd.placeholderMaxCount = i output := string(hcd.diffLineWithHighlight(lineType, `<`, `>`)) totalOverflow += hcd.placeholderOverflowCount assert.Equal(t, strings.Count(output, "