summaryrefslogtreecommitdiff
path: root/gui/internal/model/testrule_test.go
blob: 99989f4b2baeff66d009512d57f6932a20e8071b (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
65
66
67
68
69
70
71
72
73
74
75
76
// SPDX-License-Identifier: GPL-3.0-or-later

package model

import (
	"context"
	"strings"
	"testing"
)

// TestTestRule: testing one rule says which of the directory's files it
// would act on, and what would happen to each - answered from the unsaved
// text, and changing nothing (GUI design §5.3, his request 2026-09-16).
func TestTestRule(t *testing.T) {
	conf := "(path \"~/dl\")\n" +
		"(rule \"pdfs\" (when (type pdf)) (move \"Docs\") (stop))\n" +
		"(rule \"rest\" (move \"Other\"))\n"
	e, _ := sandboxDir(t, conf, map[string]string{
		"a.pdf": "one", "b.pdf": "two", "c.txt": "three",
	})
	r, err := OpenRules(e, "dl")
	if err != nil {
		t.Fatal(err)
	}

	hits, err := r.TestRule(context.Background(), "pdfs")
	if err != nil {
		t.Fatal(err)
	}
	if hits.Scanned != 3 || len(hits.Files) != 2 {
		t.Fatalf("hits = %+v", hits)
	}
	for _, h := range hits.Files {
		if !strings.HasSuffix(h.Rel, ".pdf") {
			t.Errorf("a file the rule does not match: %+v", h)
		}
		if len(h.Steps) == 0 || !strings.Contains(h.Steps[0].Dst, "Docs") {
			t.Errorf("%s: steps = %+v", h.Rel, h.Steps)
		}
	}

	// The unsaved text is what is tested, not what is on disk.
	r.SetText("(path \"~/dl\")\n(rule \"pdfs\" (when (type text)) (move \"Docs\") (stop))\n")
	hits, err = r.TestRule(context.Background(), "pdfs")
	if err != nil {
		t.Fatal(err)
	}
	if len(hits.Files) != 1 || hits.Files[0].Rel != "c.txt" {
		t.Errorf("the unsaved rule was not the one tested: %+v", hits)
	}

	// A rule that matches nothing says so rather than failing.
	r.SetText("(path \"~/dl\")\n(rule \"pdfs\" (when (type iso)) (move \"Docs\") (stop))\n")
	hits, err = r.TestRule(context.Background(), "pdfs")
	if err != nil || len(hits.Files) != 0 || hits.Scanned != 3 {
		t.Errorf("hits = %+v, err = %v", hits, err)
	}
}

// TestTestRuleRefusals: a rule that is not in the text, and text that does
// not load, are reported rather than answered.
func TestTestRuleRefusals(t *testing.T) {
	conf := "(path \"~/dl\")\n(rule \"pdfs\" (when (type pdf)) (move \"Docs\"))\n"
	e, _ := sandboxDir(t, conf, map[string]string{"a.pdf": "one"})
	r, err := OpenRules(e, "dl")
	if err != nil {
		t.Fatal(err)
	}
	if _, err := r.TestRule(context.Background(), "nosuch"); err == nil {
		t.Error("a rule that is not in the file was tested")
	}
	r.SetText("(path \"~/dl\")\n(rule \"pdfs\" (when (type pdf)) (move \"Docs/{nope}\"))\n")
	if _, err := r.TestRule(context.Background(), "pdfs"); err == nil {
		t.Error("text that does not load was tested")
	}
}