File: test_ParserSupport.py

package info (click to toggle)
python-biopython 1.45-3
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 18,192 kB
  • ctags: 12,310
  • sloc: python: 83,505; xml: 13,834; ansic: 7,015; cpp: 1,855; sql: 1,144; makefile: 179
file content (266 lines) | stat: -rw-r--r-- 8,424 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
263
264
265
266
# Copyright 1999 by Jeffrey Chang.  All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package.

import string
import sys
from Bio import File
from Bio import ParserSupport

# pyUnit

def pb(b):
    if b:
        return 1
    return 0

### TaggingConsumer

print "Running tests on TaggingConsumer"

class TestHandle:
    def write(self, s):
        print s
        
h = TestHandle()
tc = ParserSupport.TaggingConsumer(handle=h, colwidth=5)
tc.start_section()  # '***** start_section\n'
tc.test1('myline')  # 'test1: myline\n'
tc.end_section()    # '***** end_section\n'




### is_blank_line

print "Running tests on is_blank_line"

is_blank_line = lambda *args, **keywds: \
                pb(ParserSupport.is_blank_line(*args, **keywds))

print is_blank_line('\n')                              # 1
print is_blank_line('\r\n')                            # 1
print is_blank_line('\r')                              # 1
print is_blank_line('')                                # 1
print is_blank_line('', allow_spaces=1)                # 1
print is_blank_line('', allow_spaces=0)                # 1
print is_blank_line(string.whitespace, allow_spaces=1) # 1
print is_blank_line('hello')                           # 0
print is_blank_line('hello', allow_spaces=1)           # 0
print is_blank_line('hello', allow_spaces=0)           # 0
print is_blank_line(string.whitespace, allow_spaces=0) # 0


### safe_readline

print "Running tests on safe_readline"

data = """This
file"""

h = File.UndoHandle(File.StringHandle(data))

safe_readline = ParserSupport.safe_readline
print safe_readline(h)    # "This"
print safe_readline(h)    # "file"
try: safe_readline(h)
except ValueError: print "correctly failed"
else: print "ERROR, should have failed"


### safe_peekline

print "Running tests on safe_peekline"
safe_peekline = ParserSupport.safe_peekline

data = """This
file"""

h = File.UndoHandle(File.StringHandle(data))

print safe_peekline(h) # "This"
h.readline()
print safe_peekline(h) # "file"
h.readline()
try: safe_peekline(h)
except ValueError: print "correctly failed"
else: print "ERROR, should have failed"
h.saveline('hello')
print safe_peekline(h) # 'hello'


### read_and_call

print "Running tests on read_and_call"

data = """>gi|132871|sp|P19947|RL30_BACSU 50S RIBOSOMAL PROTEIN L30 (BL27)
MAKLEITLKRSVIGRPEDQRVTVRTLGLKKTNQTVVHEDNAAIRGMINKVSHLVSVKEQ
>gi|132679|sp|P19946|RL15_BACSU 50S RIBOSOMAL PROTEIN L15
MKLHELKPSEGSRKTRNRVGRGIGSGNGKTAGKGHKGQNARSGGGVRPGFEGGQMPLFQRLPKRGFTNIN
RKEYAVVNLDKLNGFAEGTEVTPELLLETGVISKLNAGVKILGNGKLEKKLTVKANKFSASAKEAVEAAG
GTAEVI


"""

h = File.UndoHandle(File.StringHandle(data))

rac = ParserSupport.read_and_call
lines = []
def m(line):
    lines.append(line)
    
rac(h, m)
print lines[-1][:10]   # '>gi|132871'
rac(h, m, start='MAKLE', end='KEQ', contains='SVIG')
rac(h, m, blank=0)

# These should be errors.  If they're not, then complain.
try: rac(h, m, blank=1)
except ValueError: print "correctly failed"
else: print "ERROR, should have failed"
try: rac(h, m, start='foobar')
except ValueError: print "correctly failed"
else: print "ERROR, should have failed"
try: rac(h, m, end='foobar')
except ValueError: print "correctly failed"
else: print "ERROR, should have failed"
try: rac(h, m, contains='foobar')
except ValueError: print "correctly failed"
else: print "ERROR, should have failed"
try: rac(h, m, blank=0)
except ValueError: print "correctly failed"
else: print "ERROR, should have failed"
        



### attempt_read_and_call

print "Running tests on attempt_read_and_call"

data = """>gi|132871|sp|P19947|RL30_BACSU 50S RIBOSOMAL PROTEIN L30 (BL27)
MAKLEITLKRSVIGRPEDQRVTVRTLGLKKTNQTVVHEDNAAIRGMINKVSHLVSVKEQ
>gi|132679|sp|P19946|RL15_BACSU 50S RIBOSOMAL PROTEIN L15
MKLHELKPSEGSRKTRNRVGRGIGSGNGKTAGKGHKGQNARSGGGVRPGFEGGQMPLFQRLPKRGFTNIN
RKEYAVVNLDKLNGFAEGTEVTPELLLETGVISKLNAGVKILGNGKLEKKLTVKANKFSASAKEAVEAAG
GTAEVI"""

h = File.UndoHandle(File.StringHandle(data))

arac = lambda *args, **keywds: \
       pb(ParserSupport.attempt_read_and_call(*args, **keywds))
lines = []
def m(line):
    lines.append(line)

print arac(h, m, contains="RIBOSOMAL PROTEIN")   # 1
print arac(h, m, start="foobar")                 # 0
print arac(h, m, blank=1)                        # 0
print arac(h, m, end="LVSVKEQ")                  # 1

# --- EventGenerator
print "Running tests on EventGenerator"

class TestConsumer:
    """Collect information from callbacks from the EventGenerator.
    """
    def __init__(self):
        self.info = {}

    def main_tag(self, content):
        raise AssertionError("We should never call this.")

    def single_tag(self, content):
        self.info['single_tag'] = content

    def multiple_tags(self, content):
        self.info['multiple_tags'] = content

def strip_and_combine(line_list):
    """Function to be sure the optional finalizer works.
    """
    stripped_line_list = map(string.strip, line_list)
    return string.join(stripped_line_list, ',')

import unittest
class EventGeneratorTest(unittest.TestCase):
    """Test the EventGenerator class to be sure callbacks are correct.
    """
    def setUp(self):
        self.interest_tags = ['single_tag', 'multiple_tags']

        import Martel

        test_format = \
           Martel.Group("main_tag",
                        Martel.Group("single_tag", Martel.Str("Spam")) +
                        Martel.Rep(Martel.Group("multiple_tags",
                                                Martel.Str("  Lots of Spam"))))
        self.test_parser = test_format.make_parser()

    def t_basic_callback(self):
        """Test the basic callback functionality.
        """
        consumer = TestConsumer()
        event_gen = ParserSupport.EventGenerator(consumer,
                                                 self.interest_tags)

        self.test_parser.setContentHandler(event_gen)
        self.test_parser.parseString("Spam" + "  Lots of Spam" +
                                     "  Lots of Spam")
        
        assert consumer.info["single_tag"] == ["Spam"], \
               "Single tag parsing failed: %s" % consumer.info["single_tag"]
        assert consumer.info["multiple_tags"] == \
               ["  Lots of Spam", "  Lots of Spam"], \
               "Multiple tag parsing failed: %s" % \
               consumer.info["multiple_tags"]

    def t_finalizer_callback(self):
        """Test the ability to pass a finalizer to the consumer.
        """
        consumer = TestConsumer()
        event_gen = ParserSupport.EventGenerator(consumer, self.interest_tags,
                                                 strip_and_combine)
        
        self.test_parser.setContentHandler(event_gen)
        self.test_parser.parseString("Spam" + "  Lots of Spam" +
                                     "  Lots of Spam")
        
        assert consumer.info["single_tag"] == "Spam", \
               "Single tag parsing failed: %s" % consumer.info["single_tag"]
        assert consumer.info["multiple_tags"] == "Lots of Spam,Lots of Spam", \
               "Multiple tag parsing failed: %s" % \
               consumer.info["multiple_tags"]

    def t_exempt_finalizer_callback(self):
        """Test the ability to exempt tags from being processed by a finalizer.
        """
        consumer = TestConsumer()
        event_gen = ParserSupport.EventGenerator(consumer, self.interest_tags,
                                                 strip_and_combine,
                                                 ["multiple_tags"])
        self.test_parser.setContentHandler(event_gen)
        self.test_parser.parseString("Spam" + "  Lots of Spam" +
                                     "  Lots of Spam")

        assert consumer.info["single_tag"] == "Spam", \
               "Single tag parsing failed: %s" % consumer.info["single_tag"]
        assert consumer.info["multiple_tags"] == \
               ["  Lots of Spam", "  Lots of Spam"], \
               "Multiple tag parsing failed: %s" % \
               consumer.info["multiple_tags"]
        

all_tests = [EventGeneratorTest]

runner = unittest.TextTestRunner(sys.stdout, verbosity = 2)

test_loader = unittest.TestLoader()
test_loader.testMethodPrefix = 't_'

for cur_test in all_tests:
    test_suite = test_loader.loadTestsFromTestCase(cur_test)
    runner.run(test_suite)