File: test_record_finder.py

package info (click to toggle)
python-cogent 2024.5.7a1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 74,600 kB
  • sloc: python: 92,479; makefile: 117; sh: 16
file content (262 lines) | stat: -rw-r--r-- 9,502 bytes parent folder | download
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
#!/usr/bin/env python
"""Unit tests for recordfinders: parsers that group the lines for a record.
"""

from unittest import TestCase

from cogent3.parse.record import RecordError
from cogent3.parse.record_finder import (
    DelimitedRecordFinder,
    LabeledRecordFinder,
    LineGrouper,
    TailedRecordFinder,
)


class TailedRecordFinderTests(TestCase):
    """Tests of the TailedRecordFinder factory function."""

    def setUp(self):
        """Define a standard TailedRecordFinder"""
        self.endswith_period = lambda x: x.endswith(".")
        self.period_tail_finder = TailedRecordFinder(self.endswith_period)

    def test_parsers(self):
        """TailedRecordFinder should split records into lines correctly"""
        lines = ">abc\ndef\nz.\n>efg\nz.".split()
        fl = self.period_tail_finder
        self.assertEqual(list(fl(lines)), [[">abc", "def", "z."], [">efg", "z."]])

    def test_parsers_empty(self):
        """TailedRecordFinder should return empty list on empty lines"""
        fl = self.period_tail_finder
        self.assertEqual(list(fl(["  ", "\n"])), [])
        self.assertEqual(list(fl([])), [])

    def test_parsers_strip(self):
        """TailedRecordFinder should trim each line correctly"""
        fl = self.period_tail_finder
        lines = ">abc  \n \t def\n  z. \t\n>efg \nz.".split("\n")
        self.assertEqual(list(fl(lines)), [[">abc", " \t def", "  z."], [">efg", "z."]])

    def test_parsers_leftover(self):
        """TailedRecordFinder should raise error or yield leftover"""
        f = self.period_tail_finder
        good = ["abc  \n", "def\n", ".\n", "ghi \n", "j."]
        blank = ["", "   ", "\t    \t\n\n"]
        bad = ["abc"]

        result = [["abc", "def", "."], ["ghi", "j."]]

        self.assertEqual(list(f(good)), result)
        self.assertEqual(list(f(good + blank)), result)
        self.assertRaises(RecordError, list, f(good + bad))

        f2 = TailedRecordFinder(self.endswith_period, strict=False)
        self.assertEqual(list(f2(good + bad)), result + [["abc"]])

    def test_parsers_ignore(self):
        """TailedRecordFinder should skip lines to ignore."""

        def never(line):
            return False

        def ignore_labels(line):
            return (not line) or line.isspace() or line.startswith("#")

        lines = ["abc", "\n", "1.", "def", "#ignore", "2."]
        self.assertEqual(
            list(TailedRecordFinder(self.endswith_period)(lines)),
            [["abc", "1."], ["def", "#ignore", "2."]],
        )
        self.assertEqual(
            list(TailedRecordFinder(self.endswith_period, ignore=never)(lines)),
            [["abc", "", "1."], ["def", "#ignore", "2."]],
        )
        self.assertEqual(
            list(TailedRecordFinder(self.endswith_period, ignore=ignore_labels)(lines)),
            [["abc", "1."], ["def", "2."]],
        )


class DelimitedRecordFinderTests(TestCase):
    """Tests of the DelimitedRecordFinder factory function."""

    def test_parsers(self):
        """DelimitedRecordFinder should split records into lines correctly"""
        lines = "abc\ndef\n//\nefg\n//".split()
        self.assertEqual(
            list(DelimitedRecordFinder("//")(lines)),
            [["abc", "def", "//"], ["efg", "//"]],
        )
        self.assertEqual(
            list(DelimitedRecordFinder("//", keep_delimiter=False)(lines)),
            [["abc", "def"], ["efg"]],
        )

    def test_parsers_empty(self):
        """DelimitedRecordFinder should return empty list on empty lines"""
        self.assertEqual(list(DelimitedRecordFinder("//")(["  ", "\n"])), [])
        self.assertEqual(list(DelimitedRecordFinder("//")([])), [])

    def test_parsers_strip(self):
        """DelimitedRecordFinder should trim each line correctly"""
        lines = "  \t   abc  \n \t   def\n  // \t\n\t\t efg \n//".split("\n")
        self.assertEqual(
            list(DelimitedRecordFinder("//")(lines)),
            [["abc", "def", "//"], ["efg", "//"]],
        )

    def test_parsers_error(self):
        """DelimitedRecordFinder should raise RecordError if trailing data"""
        good = [
            "  \t   abc  \n",
            "\t   def\n",
            "// \t\n",
            "\t\n",
            "\t efg \n",
            "\t\t//\n",
        ]
        blank = ["", "   ", "\t    \t\n\n"]
        bad = ["abc"]

        result = [["abc", "def", "//"], ["efg", "//"]]
        r = DelimitedRecordFinder("//")

        self.assertEqual(list(r(good)), result)
        self.assertEqual(list(r(good + blank)), result)
        try:
            list(r(good + bad))
        except RecordError:
            pass
        else:
            raise AssertionError("Parser failed to raise error on bad data")

        r = DelimitedRecordFinder("//", strict=False)
        self.assertEqual(list(r(good + bad)), result + [["abc"]])

    def test_parsers_ignore(self):
        """DelimitedRecordFinder should skip lines to ignore."""

        def never(line):
            return False

        def ignore_labels(line):
            return (not line) or line.isspace() or line.startswith("#")

        lines = [">abc", "\n", "1", "$$", ">def", "#ignore", "2", "$$"]
        self.assertEqual(
            list(DelimitedRecordFinder("$$")(lines)),
            [[">abc", "1", "$$"], [">def", "#ignore", "2", "$$"]],
        )
        self.assertEqual(
            list(DelimitedRecordFinder("$$", ignore=never)(lines)),
            [[">abc", "", "1", "$$"], [">def", "#ignore", "2", "$$"]],
        )
        self.assertEqual(
            list(DelimitedRecordFinder("$$", ignore=ignore_labels)(lines)),
            [[">abc", "1", "$$"], [">def", "2", "$$"]],
        )


class LabeledRecordFinderTests(TestCase):
    """Tests of the LabeledRecordFinder factory function."""

    def setUp(self):
        """Define a standard LabeledRecordFinder"""
        self.FastaLike = LabeledRecordFinder(lambda x: x.startswith(">"))

    def test_parsers(self):
        """LabeledRecordFinder should split records into lines correctly"""
        lines = ">abc\ndef\n//\n>efg\n//".split()
        fl = self.FastaLike
        self.assertEqual(list(fl(lines)), [[">abc", "def", "//"], [">efg", "//"]])

    def test_parsers_empty(self):
        """LabeledRecordFinder should return empty list on empty lines"""
        fl = self.FastaLike
        self.assertEqual(list(fl(["  ", "\n"])), [])
        self.assertEqual(list(fl([])), [])

    def test_parsers_strip(self):
        """LabeledRecordFinder should trim each line correctly"""
        fl = self.FastaLike
        lines = "  \t   >abc  \n \t   def\n  // \t\n\t\t >efg \n//".split("\n")
        self.assertEqual(list(fl(lines)), [[">abc", "def", "//"], [">efg", "//"]])

    def test_parsers_leftover(self):
        """LabeledRecordFinder should not raise RecordError if last line label"""
        fl = self.FastaLike
        good = ["  \t   >abc  \n", "\t   def\n", "\t\n", "\t >efg \n", "ghi"]
        blank = ["", "   ", "\t    \t\n\n"]
        bad = [">abc"]

        result = [[">abc", "def"], [">efg", "ghi"]]

        self.assertEqual(list(fl(good)), result)
        self.assertEqual(list(fl(good + blank)), result)
        self.assertEqual(list(fl(good + bad)), result + [[">abc"]])

    def test_parsers_ignore(self):
        """LabeledRecordFinder should skip lines to ignore."""

        def never(line):
            return False

        def ignore_labels(line):
            return (not line) or line.isspace() or line.startswith("#")

        def is_start(line):
            return line.startswith(">")

        lines = [">abc", "\n", "1", ">def", "#ignore", "2"]
        self.assertEqual(
            list(LabeledRecordFinder(is_start)(lines)),
            [[">abc", "1"], [">def", "#ignore", "2"]],
        )
        self.assertEqual(
            list(LabeledRecordFinder(is_start, ignore=never)(lines)),
            [[">abc", "", "1"], [">def", "#ignore", "2"]],
        )
        self.assertEqual(
            list(LabeledRecordFinder(is_start, ignore=ignore_labels)(lines)),
            [[">abc", "1"], [">def", "2"]],
        )


class LineGrouperTests(TestCase):
    """Tests of the LineGrouper class."""

    def test_parser(self):
        """LineGrouper should return n non-blank lines at a time"""
        good = ["  \t   >abc  \n", "\t   def\n", "\t\n", "\t >efg \n", "ghi"]
        c = LineGrouper(2)
        self.assertEqual(list(c(good)), [[">abc", "def"], [">efg", "ghi"]])
        c = LineGrouper(1)
        self.assertEqual(list(c(good)), [[">abc"], ["def"], [">efg"], ["ghi"]])
        c = LineGrouper(4)
        self.assertEqual(list(c(good)), [[">abc", "def", ">efg", "ghi"]])
        # shouldn't work if not evenly divisible
        c = LineGrouper(3)
        self.assertRaises(RecordError, list, c(good))

    def test_parser_ignore(self):
        """LineGrouper should skip lines to ignore."""

        def never(line):
            return False

        def ignore_labels(line):
            return (not line) or line.isspace() or line.startswith("#")

        lines = ["abc", "\n", "1", "def", "#ignore", "2"]
        self.assertEqual(
            list(LineGrouper(1)(lines)), [["abc"], ["1"], ["def"], ["#ignore"], ["2"]]
        )
        self.assertEqual(
            list(LineGrouper(1, ignore=never)(lines)), [[i.strip()] for i in lines]
        )
        self.assertEqual(
            list(LineGrouper(2, ignore=ignore_labels)(lines)),
            [["abc", "1"], ["def", "2"]],
        )