This repository was archived by the owner on Nov 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 253
Expand file tree
/
Copy pathtestfeedvalidator.py
More file actions
421 lines (359 loc) · 18.2 KB
/
testfeedvalidator.py
File metadata and controls
421 lines (359 loc) · 18.2 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#!/usr/bin/python2.5
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Smoke tests feed validator. Make sure it runs and returns the right things
# for a valid feed and a feed with errors.
from __future__ import absolute_import
import datetime
import feedvalidator
import os.path
import re
from six import StringIO
from tests import util
import transitfeed
import unittest
import zipfile
class FullTests(util.TempDirTestCaseBase):
feedvalidator_executable = 'feedvalidator.py'
extension_message = 'FeedValidator extension used: '
extension_name = 'None'
additional_arguments = []
def testGoodFeed(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '--latest_version',
transitfeed.__version__] + self.additional_arguments +
[self.GetPath('tests', 'data', 'good_feed')])
self.assertTrue(re.search(r'feed validated successfully', out))
self.assertFalse(re.search(r'ERROR', out))
htmlout = open('validation-results.html').read()
self.assertMatchesRegex(
self.extension_message + self.extension_name, htmlout)
self.assertTrue(re.search(r'feed validated successfully', htmlout))
self.assertFalse(re.search(r'ERROR', htmlout))
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testGoodFeedConsoleOutput(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '--latest_version',
transitfeed.__version__] + self.additional_arguments +
['--output=CONSOLE', self.GetPath('tests', 'data', 'good_feed')])
self.assertTrue(re.search(r'feed validated successfully', out))
self.assertMatchesRegex(
self.extension_message + self.extension_name, out)
self.assertFalse(re.search(r'ERROR', out))
self.assertFalse(os.path.exists('validation-results.html'))
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testMissingStops(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '--latest_version',
transitfeed.__version__] + self.additional_arguments +
[self.GetPath('tests', 'data', 'missing_stops')],
expected_retcode=1)
self.assertTrue(re.search(r'ERROR', out))
self.assertFalse(re.search(r'feed validated successfully', out))
htmlout = open('validation-results.html').read()
self.assertMatchesRegex(
self.extension_message + self.extension_name, htmlout)
self.assertTrue(re.search(r'Invalid value BEATTY_AIRPORT', htmlout))
self.assertFalse(re.search(r'feed validated successfully', htmlout))
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testMissingStopsConsoleOutput(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '-o', 'console',
'--latest_version', transitfeed.__version__] +
self.additional_arguments +
[self.GetPath('tests', 'data', 'missing_stops')],
expected_retcode=1)
self.assertMatchesRegex(
self.extension_message + self.extension_name, out)
self.assertTrue(re.search(r'ERROR', out))
self.assertFalse(re.search(r'feed validated successfully', out))
self.assertTrue(re.search(r'Invalid value BEATTY_AIRPORT', out))
self.assertFalse(os.path.exists('validation-results.html'))
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testLimitedErrors(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-l', '2', '-n',
'--latest_version', transitfeed.__version__] +
self.additional_arguments +
[self.GetPath('tests', 'data', 'missing_stops')],
expected_retcode=1)
self.assertTrue(re.search(r'ERROR', out))
self.assertFalse(re.search(r'feed validated successfully', out))
htmlout = open('validation-results.html').read()
self.assertMatchesRegex(
self.extension_message + self.extension_name, htmlout)
self.assertEquals(2, len(re.findall(r'class="problem">stop_id<', htmlout)))
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testBadDateFormat(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '--latest_version',
transitfeed.__version__] + self.additional_arguments +
[self.GetPath('tests', 'data', 'bad_date_format')],
expected_retcode=1)
self.assertTrue(re.search(r'ERROR', out))
self.assertFalse(re.search(r'feed validated successfully', out))
htmlout = open('validation-results.html').read()
self.assertMatchesRegex(
self.extension_message + self.extension_name, htmlout)
self.assertTrue(re.search(r'in field <code>start_date', htmlout))
self.assertTrue(re.search(r'in field <code>date', htmlout))
self.assertFalse(re.search(r'feed validated successfully', htmlout))
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testBadUtf8(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '--latest_version',
transitfeed.__version__] + self.additional_arguments +
[self.GetPath('tests', 'data', 'bad_utf8')],
expected_retcode=1)
self.assertTrue(re.search(r'ERROR', out))
self.assertFalse(re.search(r'feed validated successfully', out))
htmlout = open('validation-results.html').read()
self.assertMatchesRegex(
self.extension_message + self.extension_name, htmlout)
self.assertTrue(re.search(r'Unicode error', htmlout))
self.assertFalse(re.search(r'feed validated successfully', htmlout))
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testFileNotFound(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '--latest_version',
transitfeed.__version__, 'file-not-found.zip'],
expected_retcode=1)
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testBadOutputPath(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '--latest_version',
transitfeed.__version__, '-o', 'path/does/not/exist.html',
self.GetPath('tests', 'data', 'good_feed')],
expected_retcode=2)
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testCrashHandler(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '--latest_version',
transitfeed.__version__] + self.additional_arguments +
['IWantMyvalidation-crash.txt'],
expected_retcode=127)
self.assertTrue(re.search(r'Yikes', out))
self.assertFalse(re.search(r'feed validated successfully', out))
crashout = open('transitfeedcrash.txt').read()
self.assertTrue(re.search(r'For testing the feed validator crash handler',
crashout))
def testCheckVersionIsRun(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '--latest_version',
'100.100.100'] + self.additional_arguments +
[self.GetPath('tests', 'data', 'good_feed')])
self.assertTrue(re.search(r'feed validated successfully', out))
#self.assertTrue(re.search(r'A new version 100.100.100', out))
htmlout = open('validation-results.html').read()
self.assertMatchesRegex(
self.extension_message + self.extension_name, htmlout)
self.assertTrue(re.search(r'A new version 100.100.100', htmlout))
self.assertFalse(re.search(r'ERROR', htmlout))
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testCheckVersionIsRunConsoleOutput(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '-n', '-o', 'console',
'--latest_version=100.100.100'] + self.additional_arguments +
[self.GetPath('tests', 'data', 'good_feed')])
self.assertTrue(re.search(r'feed validated successfully', out))
self.assertTrue(re.search(r'A new version 100.100.100', out))
self.assertFalse(os.path.exists('validation-results.html'))
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
def testUsage(self):
(out, err) = self.CheckCallWithPath(
[self.GetPath(self.feedvalidator_executable), '--invalid_opt'],
expected_retcode=2)
self.assertMatchesRegex(r'[Uu]sage: feedvalidator(.*).py \[options\]', err)
self.assertMatchesRegex(r'wiki/FeedValidator', err)
self.assertMatchesRegex(r'--output', err) # output includes all usage info
self.assertFalse(os.path.exists('transitfeedcrash.txt'))
self.assertFalse(os.path.exists('validation-results.html'))
# Regression tests to ensure that CalendarSummary works properly
# even when the feed starts in the future or expires in less than
# 60 days
# See https://github.com/google/transitfeed/issues/204
class CalendarSummaryTestCase(util.TestCase):
# Test feeds starting in the future
def testFutureFeedDoesNotCrashCalendarSummary(self):
today = datetime.date.today()
start_date = today + datetime.timedelta(days=20)
end_date = today + datetime.timedelta(days=80)
schedule = transitfeed.Schedule()
service_period = schedule.GetDefaultServicePeriod()
service_period.SetStartDate(start_date.strftime("%Y%m%d"))
service_period.SetEndDate(end_date.strftime("%Y%m%d"))
service_period.SetWeekdayService(True)
result = feedvalidator.CalendarSummary(schedule)
self.assertEquals(0, result['max_trips'])
self.assertEquals(0, result['min_trips'])
self.assertTrue(re.search("40 service dates", result['max_trips_dates']))
# Test feeds ending in less than 60 days
def testShortFeedDoesNotCrashCalendarSummary(self):
start_date = datetime.date.today()
end_date = start_date + datetime.timedelta(days=15)
schedule = transitfeed.Schedule()
service_period = schedule.GetDefaultServicePeriod()
service_period.SetStartDate(start_date.strftime("%Y%m%d"))
service_period.SetEndDate(end_date.strftime("%Y%m%d"))
service_period.SetWeekdayService(True)
result = feedvalidator.CalendarSummary(schedule)
self.assertEquals(0, result['max_trips'])
self.assertEquals(0, result['min_trips'])
self.assertTrue(re.search("15 service dates", result['max_trips_dates']))
# Test feeds starting in the future *and* ending in less than 60 days
def testFutureAndShortFeedDoesNotCrashCalendarSummary(self):
today = datetime.date.today()
start_date = today + datetime.timedelta(days=2)
end_date = today + datetime.timedelta(days=3)
schedule = transitfeed.Schedule()
service_period = schedule.GetDefaultServicePeriod()
service_period.SetStartDate(start_date.strftime("%Y%m%d"))
service_period.SetEndDate(end_date.strftime("%Y%m%d"))
service_period.SetWeekdayService(True)
result = feedvalidator.CalendarSummary(schedule)
self.assertEquals(0, result['max_trips'])
self.assertEquals(0, result['min_trips'])
self.assertTrue(re.search("1 service date", result['max_trips_dates']))
# Test feeds without service days
def testFeedWithNoDaysDoesNotCrashCalendarSummary(self):
schedule = transitfeed.Schedule()
result = feedvalidator.CalendarSummary(schedule)
self.assertEquals({}, result)
class MockOptions:
"""Pretend to be an optparse options object suitable for testing."""
def __init__(self):
self.limit_per_type = 5
self.memory_db = True
self.check_duplicate_trips = True
self.latest_version = transitfeed.__version__
self.output = 'fake-filename.zip'
self.manual_entry = False
self.service_gap_interval = None
self.extension = None
self.error_types_ignore_list = None
class FeedValidatorTestCase(util.TempDirTestCaseBase):
def testBadEolContext(self):
"""Make sure the filename is included in the report of a bad eol."""
filename = "routes.txt"
old_zip = zipfile.ZipFile(
self.GetPath('tests', 'data', 'good_feed.zip'), 'r')
content_dict = self.ConvertZipToDict(old_zip)
old_routes = content_dict[filename]
new_routes = old_routes.replace('\n', '\r\n', 1)
self.assertNotEquals(old_routes, new_routes)
content_dict[filename] = new_routes
new_zipfile_mem = self.ConvertDictToZip(content_dict)
options = MockOptions()
output_file = StringIO()
feedvalidator.RunValidationOutputToFile(
new_zipfile_mem, options, output_file)
self.assertMatchesRegex(filename, output_file.getvalue())
class LimitPerTypeProblemReporterTestCase(util.TestCase):
def CreateLimitPerTypeProblemReporter(self, limit):
accumulator = feedvalidator.LimitPerTypeProblemAccumulator(limit)
problems = transitfeed.ProblemReporter(accumulator)
return problems
def assertProblemsAttribute(self, problem_type, class_name, attribute_name,
expected):
"""Join the value of each exception's attribute_name in order."""
problem_attribute_list = []
for e in self.problems.GetAccumulator().ProblemList(
problem_type, class_name).problems:
problem_attribute_list.append(getattr(e, attribute_name))
self.assertEquals(expected, " ".join(problem_attribute_list))
def testLimitOtherProblems(self):
"""The first N of each type should be kept."""
self.problems = self.CreateLimitPerTypeProblemReporter(2)
self.accumulator = self.problems.GetAccumulator()
self.problems.OtherProblem("e1", type=transitfeed.TYPE_ERROR)
self.problems.OtherProblem("w1", type=transitfeed.TYPE_WARNING)
self.problems.OtherProblem("e2", type=transitfeed.TYPE_ERROR)
self.problems.OtherProblem("e3", type=transitfeed.TYPE_ERROR)
self.problems.OtherProblem("w2", type=transitfeed.TYPE_WARNING)
self.assertEquals(2, self.accumulator.WarningCount())
self.assertEquals(3, self.accumulator.ErrorCount())
# These are BoundedProblemList objects
warning_bounded_list = self.accumulator.ProblemList(
transitfeed.TYPE_WARNING, "OtherProblem")
error_bounded_list = self.accumulator.ProblemList(
transitfeed.TYPE_ERROR, "OtherProblem")
self.assertEquals(2, warning_bounded_list.count)
self.assertEquals(3, error_bounded_list.count)
self.assertEquals(0, warning_bounded_list.dropped_count)
self.assertEquals(1, error_bounded_list.dropped_count)
self.assertProblemsAttribute(transitfeed.TYPE_ERROR, "OtherProblem",
"description", "e1 e2")
self.assertProblemsAttribute(transitfeed.TYPE_WARNING, "OtherProblem",
"description", "w1 w2")
def testKeepUnsorted(self):
"""An imperfect test that insort triggers ExceptionWithContext.__cmp__."""
# If ExceptionWithContext.__cmp__ doesn't trigger TypeError in
# bisect.insort then the default comparison of object id will be used. The
# id values tend to be given out in order of creation so call
# problems._Report with objects in a different order. This test should
# break if ExceptionWithContext.__cmp__ is removed or changed to return 0
# or cmp(id(self), id(y)).
exceptions = []
for i in range(20):
exceptions.append(transitfeed.OtherProblem(description="e%i" % i))
exceptions = exceptions[10:] + exceptions[:10]
self.problems = self.CreateLimitPerTypeProblemReporter(3)
self.accumulator = self.problems.GetAccumulator()
for e in exceptions:
self.problems.AddToAccumulator(e)
self.assertEquals(0, self.accumulator.WarningCount())
self.assertEquals(20, self.accumulator.ErrorCount())
bounded_list = self.accumulator.ProblemList(
transitfeed.TYPE_ERROR, "OtherProblem")
self.assertEquals(20, bounded_list.count)
self.assertEquals(17, bounded_list.dropped_count)
self.assertProblemsAttribute(transitfeed.TYPE_ERROR, "OtherProblem",
"description", "e10 e11 e12")
def testLimitSortedTooFastTravel(self):
"""Sort by decreasing distance, keeping the N greatest."""
self.problems = self.CreateLimitPerTypeProblemReporter(3)
self.accumulator = self.problems.GetAccumulator()
self.problems.TooFastTravel("t1", "prev stop", "next stop", 11230.4, 5,
None)
self.problems.TooFastTravel("t2", "prev stop", "next stop", 1120.4, 5, None)
self.problems.TooFastTravel("t3", "prev stop", "next stop", 1130.4, 5, None)
self.problems.TooFastTravel("t4", "prev stop", "next stop", 1230.4, 5, None)
self.assertEquals(0, self.accumulator.WarningCount())
self.assertEquals(4, self.accumulator.ErrorCount())
self.assertProblemsAttribute(transitfeed.TYPE_ERROR, "TooFastTravel",
"trip_id", "t1 t4 t3")
def testLimitSortedStopTooFarFromParentStation(self):
"""Sort by decreasing distance, keeping the N greatest."""
self.problems = self.CreateLimitPerTypeProblemReporter(3)
self.accumulator = self.problems.GetAccumulator()
for i, distance in enumerate((1000, 3002.0, 1500, 2434.1, 5023.21)):
self.problems.StopTooFarFromParentStation(
"s%d" % i, "S %d" % i, "p%d" % i, "P %d" % i, distance)
self.assertEquals(5, self.accumulator.WarningCount())
self.assertEquals(0, self.accumulator.ErrorCount())
self.assertProblemsAttribute(transitfeed.TYPE_WARNING,
"StopTooFarFromParentStation", "stop_id", "s4 s1 s3")
def testLimitSortedStopsTooClose(self):
"""Sort by increasing distance, keeping the N closest."""
self.problems = self.CreateLimitPerTypeProblemReporter(3)
self.accumulator = self.problems.GetAccumulator()
for i, distance in enumerate((4.0, 3.0, 2.5, 2.2, 1.0, 0.0)):
self.problems.StopsTooClose(
"Sa %d" % i, "sa%d" % i, "Sb %d" % i, "sb%d" % i, distance)
self.assertEquals(6, self.accumulator.WarningCount())
self.assertEquals(0, self.accumulator.ErrorCount())
self.assertProblemsAttribute(transitfeed.TYPE_WARNING,
"StopsTooClose", "stop_id_a", "sa5 sa4 sa3")
if __name__ == '__main__':
unittest.main()