aboutsummaryrefslogtreecommitdiff
path: root/internal/norm/fuzz_test.go
blob: 27deadcf98a4be949e058610a62ccd1525ec64fe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// SPDX-License-Identifier: GPL-3.0-or-later

package norm

import (
	"strings"
	"testing"
	"unicode/utf8"
)

// FuzzTextIdempotent: normalising text twice changes nothing more than
// normalising it once, under every case and fold setting, and so for names.
// Keywords are normalised at load and text at match time by the same
// functions; a second pass that still changed something would mean the two
// could disagree about what one normalised string is.
func FuzzTextIdempotent(f *testing.F) {
	for _, s := range []string{"Spółka Z O.O.", "ẞ straße", "a\u0301", "  tabs\tand\nlines ", "\xff", "İstanbul", "Dž", "Æsir Œuvre"} {
		f.Add(s)
	}
	f.Fuzz(func(t *testing.T, s string) {
		for _, opt := range [][2]bool{{false, false}, {true, false}, {false, true}, {true, true}} {
			once := Text(s, opt[0], opt[1])
			if twice := Text(once, opt[0], opt[1]); twice != once {
				t.Fatalf("Text(%q, %v, %v) = %q, again %q", s, opt[0], opt[1], once, twice)
			}
		}
		for _, fold := range []bool{false, true} {
			once := Name(s, fold)
			if twice := Name(once, fold); twice != once {
				t.Fatalf("Name(%q, %v) = %q, again %q", s, fold, once, twice)
			}
		}
	})
}

// FuzzFoldMapped: FoldMapped's text is always Fold's, and any part of it
// leads back to original text that folds to something holding that part.
func FuzzFoldMapped(f *testing.F) {
	for _, s := range []string{"Łódź-faktura.pdf", "straße", "áb", "\xff\xfeé", "́a", "Æsir"} {
		f.Add(s, 0, 2)
	}
	f.Fuzz(func(t *testing.T, s string, a, b int) {
		m := FoldMapped(s)
		if m.Text != Fold(s) {
			t.Fatalf("FoldMapped(%q).Text = %q, Fold = %q", s, m.Text, Fold(s))
		}
		n := len(m.Text) + 1
		a, b = (a%n+n)%n, (b%n+n)%n
		if a > b {
			a, b = b, a
		}
		// A regex match starts and ends on whole characters.
		for a < len(m.Text) && !utf8.RuneStart(m.Text[a]) {
			a--
		}
		for b < len(m.Text) && !utf8.RuneStart(m.Text[b]) {
			b--
		}
		src := m.Source(a, b)
		if !strings.Contains(Fold(src), m.Text[a:b]) {
			t.Fatalf("FoldMapped(%q).Source(%d, %d) = %q, which folds to %q, not holding %q", s, a, b, src, Fold(src), m.Text[a:b])
		}
	})
}