File: test_cli.py

package info (click to toggle)
localsearch 3.8.2-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,688 kB
  • sloc: ansic: 59,411; python: 3,774; xml: 261; perl: 106; sh: 62; makefile: 53
file content (215 lines) | stat: -rw-r--r-- 7,658 bytes parent folder | download | duplicates (2)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# Copyright (C) 2020, Sam Thursfield <sam@afuera.me.uk>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

"""
Test `tracker` commandline tool
"""

from typing import *
import dataclasses
import pathlib
import os
import re

import configuration
import fixtures
import shutil


class TestCli(fixtures.TrackerCommandLineTestCase):
    def test_search(self):
        datadir = pathlib.Path(__file__).parent.joinpath("data/content")

        # FIXME: synchronous `tracker index` isn't ready yet;
        # see https://gitlab.gnome.org/GNOME/tracker/-/issues/188
        # in the meantime we manually wait for it to finish.

        file1 = datadir.joinpath("text/Document 1.txt")
        target1 = pathlib.Path(os.path.join(self.indexed_dir, os.path.basename(file1)))
        with self.await_document_inserted(target1):
            shutil.copy(file1, self.indexed_dir)

        file2 = datadir.joinpath("text/Document 2.txt")
        target2 = pathlib.Path(os.path.join(self.indexed_dir, os.path.basename(file2)))
        with self.await_document_inserted(target2):
            shutil.copy(file2, self.indexed_dir)

        folder_name = "test-folder"
        folder_path = pathlib.Path(os.path.join(self.indexed_dir, folder_name))
        with self.await_insert_dir(folder_path):
            try:
                os.mkdir(os.path.join(self.indexed_dir, folder_name))
            except OSError as error:
                print(error)

        # FIXME: the --all should NOT be needed.
        # See: https://gitlab.gnome.org/GNOME/tracker-miners/-/issues/116
        output = self.run_cli(["localsearch", "search", "--all", "banana"])
        self.assertIn(target1.as_uri(), output)
        self.assertNotIn(target2.as_uri(), output)

        folder_output = self.run_cli(
            ["localsearch", "search", "--folders", "test-monitored"]
        )
        self.assertIn(self.indexed_dir, folder_output)
        self.assertNotIn(folder_path.as_uri(), folder_output)

    def test_search_filename(self):
        datadir = pathlib.Path(__file__).parent.joinpath("data/content")

        file1 = datadir.joinpath("text/mango.txt")
        target1 = pathlib.Path(os.path.join(self.indexed_dir, os.path.basename(file1)))
        with self.await_document_inserted(target1):
            shutil.copy(file1, self.indexed_dir)

        target2 = pathlib.Path(os.path.join(self.indexed_dir, "Document 2.txt"))

        search_output = self.run_cli(["localsearch", "search", "mango"])
        self.assertIn(target1.as_uri(), search_output)
        self.assertNotIn(target2.as_uri(), search_output)


@dataclasses.dataclass
class TagInfo:
    name: str
    description: str
    file_count: int
    files: List[str]


class TrackerTagOutputParser:
    """Manual parsing of the human-readable `localsearch tag --list` output."""

    # Adding a `--output-format=json` option to `localsearch tag` would allow
    # us to simplify this.

    def _validate_header(self, header_line):
        assert header_line.startswith("Tags")

    def _parse_tag_line(self, tag_line) -> Tuple[str, str]:
        name, description = re.match(r"  (\w+) \(([^)]+)\)", tag_line).groups()
        return (name, description)

    def parse_tag_list(self, output) -> List[TagInfo]:
        lines = output.strip().splitlines()
        self._validate_header(lines.pop(0))

        result = []
        while len(lines) > 0:
            name, description = self._parse_tag_line(lines.pop(0))
            _resource_id = lines.pop(0).strip()
            file_count = int(lines.pop(0).strip().split()[0])
            result.append(TagInfo(name, description, file_count, []))

        return result

    def parse_tag_list_with_files(self, output) -> List[TagInfo]:
        lines = output.strip().splitlines()
        self._validate_header(lines.pop(0))

        result = []
        while len(lines) > 0:
            name, description = self._parse_tag_line(lines.pop(0))
            files = []
            while len(lines) > 0 and lines[0].startswith("    "):
                files.append(lines.pop(0).strip())
            result.append(TagInfo(name, description, len(files), files))

        return result

    def assert_tag_list_empty(self, output):
        lines = output.strip().splitlines()
        assert lines[0].startswith("Tags")
        assert lines[1].find("None") >= 0
        assert len(lines) == 2


class TestCliSearch(fixtures.TrackerCommandLineTestCase):
    def test_cli_tags(self):
        """Basic "smoke test" that we can create and delete tags."""
        datadir = pathlib.Path(__file__).parent.joinpath("data/content")
        file1 = datadir.joinpath("text/Document 1.txt")
        target1 = pathlib.Path(os.path.join(self.indexed_dir, os.path.basename(file1)))
        with self.await_document_inserted(target1):
            shutil.copy(file1, self.indexed_dir)

        parser = TrackerTagOutputParser()

        # We should have no tags yet.
        output = self.run_cli(["localsearch", "tag", "--list"])
        parser.assert_tag_list_empty(output)

        # Create a tag
        output = self.run_cli(
            [
                "localsearch",
                "tag",
                target1,
                "--add=test_tag_1",
                "--description=This is my new favourite tag.",
            ]
        )

        # Assert tag is in the list.
        output = self.run_cli(["localsearch", "tag", "--list"])
        tag_infos = parser.parse_tag_list(output)
        assert len(tag_infos) == 1
        assert tag_infos[0].name == "test_tag_1"
        assert tag_infos[0].description == "This is my new favourite tag."
        assert tag_infos[0].file_count == 1

        output = self.run_cli(["localsearch", "tag", "--list", "--show-files"])
        tag_infos = parser.parse_tag_list_with_files(output)
        assert len(tag_infos) == 1
        assert tag_infos[0].name == "test_tag_1"
        assert tag_infos[0].file_count == 1
        assert tag_infos[0].files[0] == target1.as_uri()

        # Delete the tag from the file
        output = self.run_cli(
            [
                "localsearch",
                "tag",
                target1,
                "--delete=test_tag_1",
            ]
        )

	# The tag should still exist, but be assigned to no files
        output = self.run_cli(["localsearch", "tag", "--list"])
        tag_infos = parser.parse_tag_list(output)
        assert len(tag_infos) == 1
        assert tag_infos[0].name == "test_tag_1"
        assert tag_infos[0].description == "This is my new favourite tag."
        assert tag_infos[0].file_count == 0

        # Delete the tag entirely
        output = self.run_cli(
            [
                "localsearch",
                "tag",
                "--delete=test_tag_1",
            ]
        )

        # We should have no tags again.
        output = self.run_cli(["localsearch", "tag", "--list"])
        parser.assert_tag_list_empty(output)


if __name__ == "__main__":
    fixtures.tracker_test_main()