Debian Codegraph @

pecan/tests/test_base.py

raw
1 # -*- coding: utf-8 -*-
2
3 import sys
4 import os
5 import json
6 import traceback
7 import warnings
8 from io import StringIO, BytesIO
9
10 import webob
11 from webob.exc import HTTPNotFound
12 from webtest import TestApp
13
14 from pecan import (
15 Pecan, Request, Response, expose, request, response, redirect,
16 abort, make_app, override_template, render, route
17 )
18 from pecan.templating import (
19 _builtin_renderers as builtin_renderers, error_formatters, MakoRenderer
20 )
21 from pecan.decorators import accept_noncanonical
22 from pecan.tests import PecanTestCase
23
24 import unittest
25
26
27 class SampleRootController(object):
28 pass
29
30
31 class TestAppRoot(PecanTestCase):
32
33 def test_controller_lookup_by_string_path(self):
34 app = Pecan('pecan.tests.test_base.SampleRootController')
35 assert (
36 app.root and app.root.__class__.__name__ == 'SampleRootController')
37
38
39 class TestEmptyContent(PecanTestCase):
40 @property
41 def app_(self):
42 class RootController(object):
43 @expose()
44 def index(self):
45 pass
46
47 @expose()
48 def explicit_body(self):
49 response.body = b'Hello, World!'
50
51 @expose()
52 def empty_body(self):
53 response.body = b''
54
55 @expose()
56 def explicit_text(self):
57 response.text = 'Hello, World!'
58
59 @expose()
60 def empty_text(self):
61 response.text = ''
62
63 @expose()
64 def explicit_json(self):
65 response.json = {'foo': 'bar'}
66
67 @expose()
68 def explicit_json_body(self):
69 response.json_body = {'foo': 'bar'}
70
71 @expose()
72 def non_unicode(self):
73 return chr(0xc0)
74
75 return TestApp(Pecan(RootController()))
76
77 def test_empty_index(self):
78 r = self.app_.get('/')
79 self.assertEqual(r.status_int, 204)
80 self.assertNotIn('Content-Type', r.headers)
81 self.assertEqual(r.headers['Content-Length'], '0')
82 self.assertEqual(len(r.body), 0)
83
84 def test_index_with_non_unicode(self):
85 r = self.app_.get('/non_unicode/')
86 self.assertEqual(r.status_int, 200)
87
88 def test_explicit_body(self):
89 r = self.app_.get('/explicit_body/')
90 self.assertEqual(r.status_int, 200)
91 self.assertEqual(r.body, b'Hello, World!')
92
93 def test_empty_body(self):
94 r = self.app_.get('/empty_body/')
95 self.assertEqual(r.status_int, 204)
96 self.assertEqual(r.body, b'')
97
98 def test_explicit_text(self):
99 r = self.app_.get('/explicit_text/')
100 self.assertEqual(r.status_int, 200)
101 self.assertEqual(r.body, b'Hello, World!')
102
103 def test_empty_text(self):
104 r = self.app_.get('/empty_text/')
105 self.assertEqual(r.status_int, 204)
106 self.assertEqual(r.body, b'')
107
108 def test_explicit_json(self):
109 r = self.app_.get('/explicit_json/')
110 self.assertEqual(r.status_int, 200)
111 json_resp = json.loads(r.body.decode())
112 assert json_resp == {'foo': 'bar'}
113
114 def test_explicit_json_body(self):
115 r = self.app_.get('/explicit_json_body/')
116 self.assertEqual(r.status_int, 200)
117 json_resp = json.loads(r.body.decode())
118 assert json_resp == {'foo': 'bar'}
119
120
121 class TestAppIterFile(PecanTestCase):
122 @property
123 def app_(self):
124 class RootController(object):
125 @expose()
126 def index(self):
127 body = BytesIO(b'Hello, World!')
128 response.body_file = body
129
130 @expose()
131 def empty(self):
132 body = BytesIO(b'')
133 response.body_file = body
134
135 return TestApp(Pecan(RootController()))
136
137 def test_body_generator(self):
138 r = self.app_.get('/')
139 self.assertEqual(r.status_int, 200)
140 assert r.body == b'Hello, World!'
141
142 def test_empty_body_generator(self):
143 r = self.app_.get('/empty')
144 self.assertEqual(r.status_int, 204)
145 assert len(r.body) == 0
146
147
148 class TestInvalidURLEncoding(PecanTestCase):
149
150 @property
151 def app_(self):
152 class RootController(object):
153
154 @expose()
155 def _route(self, args, request):
156 assert request.path
157
158 return TestApp(Pecan(RootController()))
159
160 def test_rest_with_non_utf_8_body(self):
161 r = self.app_.get('/%aa/', expect_errors=True)
162 assert r.status_int == 400
163
164
165 class TestIndexRouting(PecanTestCase):
166
167 @property
168 def app_(self):
169 class RootController(object):
170 @expose()
171 def index(self):
172 return 'Hello, World!'
173
174 return TestApp(Pecan(RootController()))
175
176 def test_empty_root(self):
177 r = self.app_.get('/')
178 assert r.status_int == 200
179 assert r.body == b'Hello, World!'
180
181 def test_index(self):
182 r = self.app_.get('/index')
183 assert r.status_int == 200
184 assert r.body == b'Hello, World!'
185
186 def test_index_html(self):
187 r = self.app_.get('/index.html')
188 assert r.status_int == 200
189 assert r.body == b'Hello, World!'
190
191
192 class TestObjectDispatch(PecanTestCase):
193
194 @property
195 def app_(self):
196 class SubSubController(object):
197 @expose()
198 def index(self):
199 return '/sub/sub/'
200
201 @expose()
202 def deeper(self):
203 return '/sub/sub/deeper'
204
205 class SubController(object):
206 @expose()
207 def index(self):
208 return '/sub/'
209
210 @expose()
211 def deeper(self):
212 return '/sub/deeper'
213
214 sub = SubSubController()
215
216 class RootController(object):
217 @expose()
218 def index(self):
219 return '/'
220
221 @expose()
222 def deeper(self):
223 return '/deeper'
224
225 sub = SubController()
226
227 return TestApp(Pecan(RootController()))
228
229 def test_index(self):
230 r = self.app_.get('/')
231 assert r.status_int == 200
232 assert r.body == b'/'
233
234 def test_one_level(self):
235 r = self.app_.get('/deeper')
236 assert r.status_int == 200
237 assert r.body == b'/deeper'
238
239 def test_one_level_with_trailing(self):
240 r = self.app_.get('/sub/')
241 assert r.status_int == 200
242 assert r.body == b'/sub/'
243
244 def test_two_levels(self):
245 r = self.app_.get('/sub/deeper')
246 assert r.status_int == 200
247 assert r.body == b'/sub/deeper'
248
249 def test_two_levels_with_trailing(self):
250 r = self.app_.get('/sub/sub/')
251 assert r.status_int == 200
252
253 def test_three_levels(self):
254 r = self.app_.get('/sub/sub/deeper')
255 assert r.status_int == 200
256 assert r.body == b'/sub/sub/deeper'
257
258
259 class TestUnicodePathSegments(PecanTestCase):
260
261 def test_unicode_methods(self):
262 class RootController(object):
263 pass
264 setattr(RootController, '🌰', expose()(lambda self: 'Hello, World!'))
265 app = TestApp(Pecan(RootController()))
266
267 resp = app.get('/%F0%9F%8C%B0/')
268 assert resp.status_int == 200
269 assert resp.body == b'Hello, World!'
270
271 def test_unicode_child(self):
272 class ChildController(object):
273 @expose()
274 def index(self):
275 return 'Hello, World!'
276
277 class RootController(object):
278 pass
279 setattr(RootController, '🌰', ChildController())
280 app = TestApp(Pecan(RootController()))
281
282 resp = app.get('/%F0%9F%8C%B0/')
283 assert resp.status_int == 200
284 assert resp.body == b'Hello, World!'
285
286
287 class TestLookups(PecanTestCase):
288
289 @property
290 def app_(self):
291 class LookupController(object):
292 def __init__(self, someID):
293 self.someID = someID
294
295 @expose()
296 def index(self):
297 return '/%s' % self.someID
298
299 @expose()
300 def name(self):
301 return '/%s/name' % self.someID
302
303 class RootController(object):
304 @expose()
305 def index(self):
306 return '/'
307
308 @expose()
309 def _lookup(self, someID, *remainder):
310 return LookupController(someID), remainder
311
312 return TestApp(Pecan(RootController()))
313
314 def test_index(self):
315 r = self.app_.get('/')
316 assert r.status_int == 200
317 assert r.body == b'/'
318
319 def test_lookup(self):
320 r = self.app_.get('/100/')
321 assert r.status_int == 200
322 assert r.body == b'/100'
323
324 def test_lookup_with_method(self):
325 r = self.app_.get('/100/name')
326 assert r.status_int == 200
327 assert r.body == b'/100/name'
328
329 def test_lookup_with_wrong_argspec(self):
330 class RootController(object):
331 @expose()
332 def _lookup(self, someID):
333 return 'Bad arg spec' # pragma: nocover
334
335 app = TestApp(Pecan(RootController()))
336 r = app.get('/foo/bar', expect_errors=True)
337 assert r.status_int == 404
338
339 def test_lookup_with_wrong_return(self):
340 class RootController(object):
341 @expose()
342 def _lookup(self, someID, *remainder):
343 return 1
344
345 app = TestApp(Pecan(RootController()))
346 self.assertRaises(TypeError,
347 app.get,
348 '/foo/bar', expect_errors=True)
349
350
351 class TestCanonicalLookups(PecanTestCase):
352
353 @property
354 def app_(self):
355 class LookupController(object):
356 def __init__(self, someID):
357 self.someID = someID
358
359 @expose()
360 def index(self):
361 return self.someID
362
363 class UserController(object):
364 @expose()
365 def _lookup(self, someID, *remainder):
366 return LookupController(someID), remainder
367
368 class RootController(object):
369 users = UserController()
370
371 return TestApp(Pecan(RootController()))
372
373 def test_canonical_lookup(self):
374 assert self.app_.get('/users', expect_errors=404).status_int == 404
375 assert self.app_.get('/users/', expect_errors=404).status_int == 404
376 assert self.app_.get('/users/100').status_int == 302
377 assert self.app_.get('/users/100/').body == b'100'
378
379
380 class TestControllerArguments(PecanTestCase):
381
382 @property
383 def app_(self):
384 class RootController(object):
385 @expose()
386 def index(self, id):
387 return 'index: %s' % id
388
389 @expose()
390 def multiple(self, one, two):
391 return 'multiple: %s, %s' % (one, two)
392
393 @expose()
394 def optional(self, id=None):
395 return 'optional: %s' % str(id)
396
397 @expose()
398 def multiple_optional(self, one=None, two=None, three=None):
399 return 'multiple_optional: %s, %s, %s' % (one, two, three)
400
401 @expose()
402 def variable_args(self, *args):
403 return 'variable_args: %s' % ', '.join(args)
404
405 @expose()
406 def variable_kwargs(self, **kwargs):
407 data = [
408 '%s=%s' % (key, kwargs[key])
409 for key in sorted(kwargs.keys())
410 ]
411 return 'variable_kwargs: %s' % ', '.join(data)
412
413 @expose()
414 def variable_all(self, *args, **kwargs):
415 data = [
416 '%s=%s' % (key, kwargs[key])
417 for key in sorted(kwargs.keys())
418 ]
419 return 'variable_all: %s' % ', '.join(list(args) + data)
420
421 @expose()
422 def eater(self, id, dummy=None, *args, **kwargs):
423 data = [
424 '%s=%s' % (key, kwargs[key])
425 for key in sorted(kwargs.keys())
426 ]
427 return 'eater: %s, %s, %s' % (
428 id,
429 dummy,
430 ', '.join(list(args) + data)
431 )
432
433 @staticmethod
434 @expose()
435 def static(id):
436 return "id is %s" % id
437
438 @expose()
439 def _route(self, args, request):
440 if hasattr(self, args[0]):
441 return getattr(self, args[0]), args[1:]
442 else:
443 return self.index, args
444
445 return TestApp(Pecan(RootController()))
446
447 def test_required_argument(self):
448 try:
449 r = self.app_.get('/')
450 assert r.status_int != 200 # pragma: nocover
451 except Exception as ex:
452 assert isinstance(ex, TypeError)
453 assert ex.args[0] in (
454 "index() takes exactly 2 arguments (1 given)",
455 "index() missing 1 required positional argument: 'id'",
456 (
457 "TestControllerArguments.app_.<locals>.RootController."
458 "index() missing 1 required positional argument: 'id'"
459 ),
460 ) # this messaging changed in Python 3.3 and again in Python 3.10
461
462 def test_single_argument(self):
463 r = self.app_.get('/1')
464 assert r.status_int == 200
465 assert r.body == b'index: 1'
466
467 def test_single_argument_with_encoded_url(self):
468 r = self.app_.get('/This%20is%20a%20test%21')
469 assert r.status_int == 200
470 assert r.body == b'index: This is a test!'
471
472 def test_single_argument_with_plus(self):
473 r = self.app_.get('/foo+bar')
474 assert r.status_int == 200
475 assert r.body == b'index: foo+bar'
476
477 def test_single_argument_with_encoded_plus(self):
478 r = self.app_.get('/foo%2Bbar')
479 assert r.status_int == 200
480 assert r.body == b'index: foo+bar'
481
482 def test_two_arguments(self):
483 r = self.app_.get('/1/dummy', status=404)
484 assert r.status_int == 404
485
486 def test_keyword_argument(self):
487 r = self.app_.get('/?id=2')
488 assert r.status_int == 200
489 assert r.body == b'index: 2'
490
491 def test_keyword_argument_with_encoded_url(self):
492 r = self.app_.get('/?id=This%20is%20a%20test%21')
493 assert r.status_int == 200
494 assert r.body == b'index: This is a test!'
495
496 def test_keyword_argument_with_plus(self):
497 r = self.app_.get('/?id=foo+bar')
498 assert r.status_int == 200
499 assert r.body == b'index: foo bar'
500
501 def test_keyword_argument_with_encoded_plus(self):
502 r = self.app_.get('/?id=foo%2Bbar')
503 assert r.status_int == 200
504 assert r.body == b'index: foo+bar'
505
506 def test_argument_and_keyword_argument(self):
507 r = self.app_.get('/3?id=three')
508 assert r.status_int == 200
509 assert r.body == b'index: 3'
510
511 def test_encoded_argument_and_keyword_argument(self):
512 r = self.app_.get('/This%20is%20a%20test%21?id=three')
513 assert r.status_int == 200
514 assert r.body == b'index: This is a test!'
515
516 def test_explicit_kwargs(self):
517 r = self.app_.post('/', {'id': '4'})
518 assert r.status_int == 200
519 assert r.body == b'index: 4'
520
521 def test_path_with_explicit_kwargs(self):
522 r = self.app_.post('/4', {'id': 'four'})
523 assert r.status_int == 200
524 assert r.body == b'index: 4'
525
526 def test_explicit_json_kwargs(self):
527 r = self.app_.post_json('/', {'id': '4'})
528 assert r.status_int == 200
529 assert r.body == b'index: 4'
530
531 def test_path_with_explicit_json_kwargs(self):
532 r = self.app_.post_json('/4', {'id': 'four'})
533 assert r.status_int == 200
534 assert r.body == b'index: 4'
535
536 def test_multiple_kwargs(self):
537 r = self.app_.get('/?id=5&dummy=dummy')
538 assert r.status_int == 200
539 assert r.body == b'index: 5'
540
541 def test_kwargs_from_root(self):
542 r = self.app_.post('/', {'id': '6', 'dummy': 'dummy'})
543 assert r.status_int == 200
544 assert r.body == b'index: 6'
545
546 def test_json_kwargs_from_root(self):
547 r = self.app_.post_json('/', {'id': '6', 'dummy': 'dummy'})
548 assert r.status_int == 200
549 assert r.body == b'index: 6'
550
551 # multiple args
552
553 def test_multiple_positional_arguments(self):
554 r = self.app_.get('/multiple/one/two')
555 assert r.status_int == 200
556 assert r.body == b'multiple: one, two'
557
558 def test_multiple_positional_arguments_with_url_encode(self):
559 r = self.app_.get('/multiple/One%20/Two%21')
560 assert r.status_int == 200
561 assert r.body == b'multiple: One , Two!'
562
563 def test_multiple_positional_arguments_with_kwargs(self):
564 r = self.app_.get('/multiple?one=three&two=four')
565 assert r.status_int == 200
566 assert r.body == b'multiple: three, four'
567
568 def test_multiple_positional_arguments_with_url_encoded_kwargs(self):
569 r = self.app_.get('/multiple?one=Three%20&two=Four%20%21')
570 assert r.status_int == 200
571 assert r.body == b'multiple: Three , Four !'
572
573 def test_positional_args_with_dictionary_kwargs(self):
574 r = self.app_.post('/multiple', {'one': 'five', 'two': 'six'})
575 assert r.status_int == 200
576 assert r.body == b'multiple: five, six'
577
578 def test_positional_args_with_json_kwargs(self):
579 r = self.app_.post_json('/multiple', {'one': 'five', 'two': 'six'})
580 assert r.status_int == 200
581 assert r.body == b'multiple: five, six'
582
583 def test_positional_args_with_url_encoded_dictionary_kwargs(self):
584 r = self.app_.post('/multiple', {'one': 'Five%20', 'two': 'Six%20%21'})
585 assert r.status_int == 200
586 assert r.body == b'multiple: Five%20, Six%20%21'
587
588 # optional arg
589 def test_optional_arg(self):
590 r = self.app_.get('/optional')
591 assert r.status_int == 200
592 assert r.body == b'optional: None'
593
594 def test_multiple_optional(self):
595 r = self.app_.get('/optional/1')
596 assert r.status_int == 200
597 assert r.body == b'optional: 1'
598
599 def test_multiple_optional_url_encoded(self):
600 r = self.app_.get('/optional/Some%20Number')
601 assert r.status_int == 200
602 assert r.body == b'optional: Some Number'
603
604 def test_multiple_optional_missing(self):
605 r = self.app_.get('/optional/2/dummy', status=404)
606 assert r.status_int == 404
607
608 def test_multiple_with_kwargs(self):
609 r = self.app_.get('/optional?id=2')
610 assert r.status_int == 200
611 assert r.body == b'optional: 2'
612
613 def test_multiple_with_url_encoded_kwargs(self):
614 r = self.app_.get('/optional?id=Some%20Number')
615 assert r.status_int == 200
616 assert r.body == b'optional: Some Number'
617
618 def test_multiple_args_with_url_encoded_kwargs(self):
619 r = self.app_.get('/optional/3?id=three')
620 assert r.status_int == 200
621 assert r.body == b'optional: 3'
622
623 def test_url_encoded_positional_args(self):
624 r = self.app_.get('/optional/Some%20Number?id=three')
625 assert r.status_int == 200
626 assert r.body == b'optional: Some Number'
627
628 def test_optional_arg_with_kwargs(self):
629 r = self.app_.post('/optional', {'id': '4'})
630 assert r.status_int == 200
631 assert r.body == b'optional: 4'
632
633 def test_optional_arg_with_json_kwargs(self):
634 r = self.app_.post_json('/optional', {'id': '4'})
635 assert r.status_int == 200
636 assert r.body == b'optional: 4'
637
638 def test_optional_arg_with_url_encoded_kwargs(self):
639 r = self.app_.post('/optional', {'id': 'Some%20Number'})
640 assert r.status_int == 200
641 assert r.body == b'optional: Some%20Number'
642
643 def test_multiple_positional_arguments_with_dictionary_kwargs(self):
644 r = self.app_.post('/optional/5', {'id': 'five'})
645 assert r.status_int == 200
646 assert r.body == b'optional: 5'
647
648 def test_multiple_positional_arguments_with_json_kwargs(self):
649 r = self.app_.post_json('/optional/5', {'id': 'five'})
650 assert r.status_int == 200
651 assert r.body == b'optional: 5'
652
653 def test_multiple_positional_url_encoded_arguments_with_kwargs(self):
654 r = self.app_.post('/optional/Some%20Number', {'id': 'five'})
655 assert r.status_int == 200
656 assert r.body == b'optional: Some Number'
657
658 def test_optional_arg_with_multiple_kwargs(self):
659 r = self.app_.get('/optional?id=6&dummy=dummy')
660 assert r.status_int == 200
661 assert r.body == b'optional: 6'
662
663 def test_optional_arg_with_multiple_url_encoded_kwargs(self):
664 r = self.app_.get('/optional?id=Some%20Number&dummy=dummy')
665 assert r.status_int == 200
666 assert r.body == b'optional: Some Number'
667
668 def test_optional_arg_with_multiple_dictionary_kwargs(self):
669 r = self.app_.post('/optional', {'id': '7', 'dummy': 'dummy'})
670 assert r.status_int == 200
671 assert r.body == b'optional: 7'
672
673 def test_optional_arg_with_multiple_json_kwargs(self):
674 r = self.app_.post_json('/optional', {'id': '7', 'dummy': 'dummy'})
675 assert r.status_int == 200
676 assert r.body == b'optional: 7'
677
678 def test_optional_arg_with_multiple_url_encoded_dictionary_kwargs(self):
679 r = self.app_.post('/optional', {
680 'id': 'Some%20Number',
681 'dummy': 'dummy'
682 })
683 assert r.status_int == 200
684 assert r.body == b'optional: Some%20Number'
685
686 # multiple optional args
687
688 def test_multiple_optional_positional_args(self):
689 r = self.app_.get('/multiple_optional')
690 assert r.status_int == 200
691 assert r.body == b'multiple_optional: None, None, None'
692
693 def test_multiple_optional_positional_args_one_arg(self):
694 r = self.app_.get('/multiple_optional/1')
695 assert r.status_int == 200
696 assert r.body == b'multiple_optional: 1, None, None'
697
698 def test_multiple_optional_positional_args_one_url_encoded_arg(self):
699 r = self.app_.get('/multiple_optional/One%21')
700 assert r.status_int == 200
701 assert r.body == b'multiple_optional: One!, None, None'
702
703 def test_multiple_optional_positional_args_all_args(self):
704 r = self.app_.get('/multiple_optional/1/2/3')
705 assert r.status_int == 200
706 assert r.body == b'multiple_optional: 1, 2, 3'
707
708 def test_multiple_optional_positional_args_all_url_encoded_args(self):
709 r = self.app_.get('/multiple_optional/One%21/Two%21/Three%21')
710 assert r.status_int == 200
711 assert r.body == b'multiple_optional: One!, Two!, Three!'
712
713 def test_multiple_optional_positional_args_too_many_args(self):
714 r = self.app_.get('/multiple_optional/1/2/3/dummy', status=404)
715 assert r.status_int == 404
716
717 def test_multiple_optional_positional_args_with_kwargs(self):
718 r = self.app_.get('/multiple_optional?one=1')
719 assert r.status_int == 200
720 assert r.body == b'multiple_optional: 1, None, None'
721
722 def test_multiple_optional_positional_args_with_url_encoded_kwargs(self):
723 r = self.app_.get('/multiple_optional?one=One%21')
724 assert r.status_int == 200
725 assert r.body == b'multiple_optional: One!, None, None'
726
727 def test_multiple_optional_positional_args_with_string_kwargs(self):
728 r = self.app_.get('/multiple_optional/1?one=one')
729 assert r.status_int == 200
730 assert r.body == b'multiple_optional: 1, None, None'
731
732 def test_multiple_optional_positional_args_with_encoded_str_kwargs(self):
733 r = self.app_.get('/multiple_optional/One%21?one=one')
734 assert r.status_int == 200
735 assert r.body == b'multiple_optional: One!, None, None'
736
737 def test_multiple_optional_positional_args_with_dict_kwargs(self):
738 r = self.app_.post('/multiple_optional', {'one': '1'})
739 assert r.status_int == 200
740 assert r.body == b'multiple_optional: 1, None, None'
741
742 def test_multiple_optional_positional_args_with_json_kwargs(self):
743 r = self.app_.post_json('/multiple_optional', {'one': '1'})
744 assert r.status_int == 200
745 assert r.body == b'multiple_optional: 1, None, None'
746
747 def test_multiple_optional_positional_args_with_encoded_dict_kwargs(self):
748 r = self.app_.post('/multiple_optional', {'one': 'One%21'})
749 assert r.status_int == 200
750 assert r.body == b'multiple_optional: One%21, None, None'
751
752 def test_multiple_optional_positional_args_and_dict_kwargs(self):
753 r = self.app_.post('/multiple_optional/1', {'one': 'one'})
754 assert r.status_int == 200
755 assert r.body == b'multiple_optional: 1, None, None'
756
757 def test_multiple_optional_positional_args_and_json_kwargs(self):
758 r = self.app_.post_json('/multiple_optional/1', {'one': 'one'})
759 assert r.status_int == 200
760 assert r.body == b'multiple_optional: 1, None, None'
761
762 def test_multiple_optional_encoded_positional_args_and_dict_kwargs(self):
763 r = self.app_.post('/multiple_optional/One%21', {'one': 'one'})
764 assert r.status_int == 200
765 assert r.body == b'multiple_optional: One!, None, None'
766
767 def test_multiple_optional_args_with_multiple_kwargs(self):
768 r = self.app_.get('/multiple_optional?one=1&two=2&three=3&four=4')
769 assert r.status_int == 200
770 assert r.body == b'multiple_optional: 1, 2, 3'
771
772 def test_multiple_optional_args_with_multiple_encoded_kwargs(self):
773 r = self.app_.get(
774 '/multiple_optional?one=One%21&two=Two%21&three=Three%21&four=4'
775 )
776 assert r.status_int == 200
777 assert r.body == b'multiple_optional: One!, Two!, Three!'
778
779 def test_multiple_optional_args_with_multiple_dict_kwargs(self):
780 r = self.app_.post(
781 '/multiple_optional',
782 {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
783 )
784 assert r.status_int == 200
785 assert r.body == b'multiple_optional: 1, 2, 3'
786
787 def test_multiple_optional_args_with_multiple_json_kwargs(self):
788 r = self.app_.post_json(
789 '/multiple_optional',
790 {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
791 )
792 assert r.status_int == 200
793 assert r.body == b'multiple_optional: 1, 2, 3'
794
795 def test_multiple_optional_args_with_multiple_encoded_dict_kwargs(self):
796 r = self.app_.post(
797 '/multiple_optional',
798 {
799 'one': 'One%21',
800 'two': 'Two%21',
801 'three': 'Three%21',
802 'four': '4'
803 }
804 )
805 assert r.status_int == 200
806 assert r.body == b'multiple_optional: One%21, Two%21, Three%21'
807
808 def test_multiple_optional_args_with_last_kwarg(self):
809 r = self.app_.get('/multiple_optional?three=3')
810 assert r.status_int == 200
811 assert r.body == b'multiple_optional: None, None, 3'
812
813 def test_multiple_optional_args_with_last_encoded_kwarg(self):
814 r = self.app_.get('/multiple_optional?three=Three%21')
815 assert r.status_int == 200
816 assert r.body == b'multiple_optional: None, None, Three!'
817
818 def test_multiple_optional_args_with_middle_arg(self):
819 r = self.app_.get('/multiple_optional', {'two': '2'})
820 assert r.status_int == 200
821 assert r.body == b'multiple_optional: None, 2, None'
822
823 def test_variable_args(self):
824 r = self.app_.get('/variable_args')
825 assert r.status_int == 200
826 assert r.body == b'variable_args: '
827
828 def test_multiple_variable_args(self):
829 r = self.app_.get('/variable_args/1/dummy')
830 assert r.status_int == 200
831 assert r.body == b'variable_args: 1, dummy'
832
833 def test_multiple_encoded_variable_args(self):
834 r = self.app_.get('/variable_args/Testing%20One%20Two/Three%21')
835 assert r.status_int == 200
836 assert r.body == b'variable_args: Testing One Two, Three!'
837
838 def test_variable_args_with_kwargs(self):
839 r = self.app_.get('/variable_args?id=2&dummy=dummy')
840 assert r.status_int == 200
841 assert r.body == b'variable_args: '
842
843 def test_variable_args_with_dict_kwargs(self):
844 r = self.app_.post('/variable_args', {'id': '3', 'dummy': 'dummy'})
845 assert r.status_int == 200
846 assert r.body == b'variable_args: '
847
848 def test_variable_args_with_json_kwargs(self):
849 r = self.app_.post_json(
850 '/variable_args',
851 {'id': '3', 'dummy': 'dummy'}
852 )
853 assert r.status_int == 200
854 assert r.body == b'variable_args: '
855
856 def test_variable_kwargs(self):
857 r = self.app_.get('/variable_kwargs')
858 assert r.status_int == 200
859 assert r.body == b'variable_kwargs: '
860
861 def test_multiple_variable_kwargs(self):
862 r = self.app_.get('/variable_kwargs/1/dummy', status=404)
863 assert r.status_int == 404
864
865 def test_multiple_variable_kwargs_with_explicit_kwargs(self):
866 r = self.app_.get('/variable_kwargs?id=2&dummy=dummy')
867 assert r.status_int == 200
868 assert r.body == b'variable_kwargs: dummy=dummy, id=2'
869
870 def test_multiple_variable_kwargs_with_explicit_encoded_kwargs(self):
871 r = self.app_.get(
872 '/variable_kwargs?id=Two%21&dummy=This%20is%20a%20test'
873 )
874 assert r.status_int == 200
875 assert r.body == b'variable_kwargs: dummy=This is a test, id=Two!'
876
877 def test_multiple_variable_kwargs_with_dict_kwargs(self):
878 r = self.app_.post('/variable_kwargs', {'id': '3', 'dummy': 'dummy'})
879 assert r.status_int == 200
880 assert r.body == b'variable_kwargs: dummy=dummy, id=3'
881
882 def test_multiple_variable_kwargs_with_json_kwargs(self):
883 r = self.app_.post_json(
884 '/variable_kwargs',
885 {'id': '3', 'dummy': 'dummy'}
886 )
887 assert r.status_int == 200
888 assert r.body == b'variable_kwargs: dummy=dummy, id=3'
889
890 def test_multiple_variable_kwargs_with_encoded_dict_kwargs(self):
891 r = self.app_.post(
892 '/variable_kwargs',
893 {'id': 'Three%21', 'dummy': 'This%20is%20a%20test'}
894 )
895 assert r.status_int == 200
896 result = b'variable_kwargs: dummy=This%20is%20a%20test, id=Three%21'
897 assert r.body == result
898
899 def test_variable_all(self):
900 r = self.app_.get('/variable_all')
901 assert r.status_int == 200
902 assert r.body == b'variable_all: '
903
904 def test_variable_all_with_one_extra(self):
905 r = self.app_.get('/variable_all/1')
906 assert r.status_int == 200
907 assert r.body == b'variable_all: 1'
908
909 def test_variable_all_with_two_extras(self):
910 r = self.app_.get('/variable_all/2/dummy')
911 assert r.status_int == 200
912 assert r.body == b'variable_all: 2, dummy'
913
914 def test_variable_mixed(self):
915 r = self.app_.get('/variable_all/3?month=1&day=12')
916 assert r.status_int == 200
917 assert r.body == b'variable_all: 3, day=12, month=1'
918
919 def test_variable_mixed_explicit(self):
920 r = self.app_.get('/variable_all/4?id=four&month=1&day=12')
921 assert r.status_int == 200
922 assert r.body == b'variable_all: 4, day=12, id=four, month=1'
923
924 def test_variable_post(self):
925 r = self.app_.post('/variable_all/5/dummy')
926 assert r.status_int == 200
927 assert r.body == b'variable_all: 5, dummy'
928
929 def test_variable_post_with_kwargs(self):
930 r = self.app_.post('/variable_all/6', {'month': '1', 'day': '12'})
931 assert r.status_int == 200
932 assert r.body == b'variable_all: 6, day=12, month=1'
933
934 def test_variable_post_with_json_kwargs(self):
935 r = self.app_.post_json(
936 '/variable_all/6',
937 {'month': '1', 'day': '12'}
938 )
939 assert r.status_int == 200
940 assert r.body == b'variable_all: 6, day=12, month=1'
941
942 def test_variable_post_mixed(self):
943 r = self.app_.post(
944 '/variable_all/7',
945 {'id': 'seven', 'month': '1', 'day': '12'}
946 )
947 assert r.status_int == 200
948 assert r.body == b'variable_all: 7, day=12, id=seven, month=1'
949
950 def test_variable_post_mixed_with_json(self):
951 r = self.app_.post_json(
952 '/variable_all/7',
953 {'id': 'seven', 'month': '1', 'day': '12'}
954 )
955 assert r.status_int == 200
956 assert r.body == b'variable_all: 7, day=12, id=seven, month=1'
957
958 def test_duplicate_query_parameters_GET(self):
959 r = self.app_.get('/variable_kwargs?list=1&list=2')
960 assert r.status_int == 200
961 assert r.body == b"variable_kwargs: list=['1', '2']"
962
963 def test_duplicate_query_parameters_POST(self):
964 r = self.app_.post('/variable_kwargs',
965 {'list': ['1', '2']})
966 assert r.status_int == 200
967 assert r.body == b"variable_kwargs: list=['1', '2']"
968
969 def test_duplicate_query_parameters_POST_mixed(self):
970 r = self.app_.post('/variable_kwargs?list=1&list=2',
971 {'list': ['3', '4']})
972 assert r.status_int == 200
973 assert r.body == b"variable_kwargs: list=['1', '2', '3', '4']"
974
975 def test_duplicate_query_parameters_POST_mixed_json(self):
976 r = self.app_.post('/variable_kwargs?list=1&list=2',
977 {'list': 3})
978 assert r.status_int == 200
979 assert r.body == b"variable_kwargs: list=['1', '2', '3']"
980
981 def test_staticmethod(self):
982 r = self.app_.get('/static/foobar')
983 assert r.status_int == 200
984 assert r.body == b'id is foobar'
985
986 def test_no_remainder(self):
987 try:
988 r = self.app_.get('/eater')
989 assert r.status_int != 200 # pragma: nocover
990 except Exception as ex:
991 assert isinstance(ex, TypeError)
992 assert ex.args[0] in (
993 "eater() takes exactly 2 arguments (1 given)",
994 "eater() missing 1 required positional argument: 'id'",
995 (
996 "TestControllerArguments.app_.<locals>.RootController."
997 "eater() missing 1 required positional argument: 'id'"
998 ),
999 ) # this messaging changed in Python 3.3 and again in Python 3.10
1000
1001 def test_one_remainder(self):
1002 r = self.app_.get('/eater/1')
1003 assert r.status_int == 200
1004 assert r.body == b'eater: 1, None, '
1005
1006 def test_two_remainders(self):
1007 r = self.app_.get('/eater/2/dummy')
1008 assert r.status_int == 200
1009 assert r.body == b'eater: 2, dummy, '
1010
1011 def test_many_remainders(self):
1012 r = self.app_.get('/eater/3/dummy/foo/bar')
1013 assert r.status_int == 200
1014 assert r.body == b'eater: 3, dummy, foo, bar'
1015
1016 def test_remainder_with_kwargs(self):
1017 r = self.app_.get('/eater/4?month=1&day=12')
1018 assert r.status_int == 200
1019 assert r.body == b'eater: 4, None, day=12, month=1'
1020
1021 def test_remainder_with_many_kwargs(self):
1022 r = self.app_.get('/eater/5?id=five&month=1&day=12&dummy=dummy')
1023 assert r.status_int == 200
1024 assert r.body == b'eater: 5, dummy, day=12, month=1'
1025
1026 def test_post_remainder(self):
1027 r = self.app_.post('/eater/6')
1028 assert r.status_int == 200
1029 assert r.body == b'eater: 6, None, '
1030
1031 def test_post_three_remainders(self):
1032 r = self.app_.post('/eater/7/dummy')
1033 assert r.status_int == 200
1034 assert r.body == b'eater: 7, dummy, '
1035
1036 def test_post_many_remainders(self):
1037 r = self.app_.post('/eater/8/dummy/foo/bar')
1038 assert r.status_int == 200
1039 assert r.body == b'eater: 8, dummy, foo, bar'
1040
1041 def test_post_remainder_with_kwargs(self):
1042 r = self.app_.post('/eater/9', {'month': '1', 'day': '12'})
1043 assert r.status_int == 200
1044 assert r.body == b'eater: 9, None, day=12, month=1'
1045
1046 def test_post_empty_remainder_with_json_kwargs(self):
1047 r = self.app_.post_json('/eater/9/', {'month': '1', 'day': '12'})
1048 assert r.status_int == 200
1049 assert r.body == b'eater: 9, None, day=12, month=1'
1050
1051 def test_post_remainder_with_json_kwargs(self):
1052 r = self.app_.post_json('/eater/9', {'month': '1', 'day': '12'})
1053 assert r.status_int == 200
1054 assert r.body == b'eater: 9, None, day=12, month=1'
1055
1056 def test_post_many_remainders_with_many_kwargs(self):
1057 r = self.app_.post(
1058 '/eater/10',
1059 {'id': 'ten', 'month': '1', 'day': '12', 'dummy': 'dummy'}
1060 )
1061 assert r.status_int == 200
1062 assert r.body == b'eater: 10, dummy, day=12, month=1'
1063
1064 def test_post_many_remainders_with_many_json_kwargs(self):
1065 r = self.app_.post_json(
1066 '/eater/10',
1067 {'id': 'ten', 'month': '1', 'day': '12', 'dummy': 'dummy'}
1068 )
1069 assert r.status_int == 200
1070 assert r.body == b'eater: 10, dummy, day=12, month=1'
1071
1072
1073 class TestDefaultErrorRendering(PecanTestCase):
1074
1075 def test_plain_error(self):
1076 class RootController(object):
1077 pass
1078
1079 app = TestApp(Pecan(RootController()))
1080 r = app.get('/', status=404)
1081 assert r.status_int == 404
1082 assert r.content_type == 'text/plain'
1083 assert r.body == HTTPNotFound().plain_body({}).encode('utf-8')
1084
1085 def test_html_error(self):
1086 class RootController(object):
1087 pass
1088
1089 app = TestApp(Pecan(RootController()))
1090 r = app.get('/', headers={'Accept': 'text/html'}, status=404)
1091 assert r.status_int == 404
1092 assert r.content_type == 'text/html'
1093 assert r.body == HTTPNotFound().html_body({}).encode('utf-8')
1094
1095 def test_json_error(self):
1096 class RootController(object):
1097 pass
1098
1099 app = TestApp(Pecan(RootController()))
1100 r = app.get('/', headers={'Accept': 'application/json'}, status=404)
1101 assert r.status_int == 404
1102 json_resp = json.loads(r.body.decode())
1103 assert json_resp['code'] == 404
1104 assert json_resp['description'] is None
1105 assert json_resp['title'] == 'Not Found'
1106 assert r.content_type == 'application/json'
1107
1108
1109 class TestAbort(PecanTestCase):
1110
1111 def test_abort(self):
1112 class RootController(object):
1113 @expose()
1114 def index(self):
1115 abort(404)
1116
1117 app = TestApp(Pecan(RootController()))
1118 r = app.get('/', status=404)
1119 assert r.status_int == 404
1120
1121 def test_abort_with_detail(self):
1122 class RootController(object):
1123 @expose()
1124 def index(self):
1125 abort(status_code=401, detail='Not Authorized')
1126
1127 app = TestApp(Pecan(RootController()))
1128 r = app.get('/', status=401)
1129 assert r.status_int == 401
1130
1131 def test_abort_keeps_traceback(self):
1132 last_exc, last_traceback = None, None
1133
1134 try:
1135 try:
1136 raise Exception('Bottom Exception')
1137 except Exception:
1138 abort(404)
1139 except Exception:
1140 last_exc, _, last_traceback = sys.exc_info()
1141
1142 assert last_exc is HTTPNotFound
1143 assert 'Bottom Exception' in traceback.format_tb(last_traceback)[-1]
1144
1145
1146 class TestScriptName(PecanTestCase):
1147
1148 def setUp(self):
1149 super(TestScriptName, self).setUp()
1150 self.environ = {'SCRIPT_NAME': '/foo'}
1151
1152 def test_handle_script_name(self):
1153 class RootController(object):
1154 @expose()
1155 def index(self):
1156 return 'Root Index'
1157
1158 app = TestApp(Pecan(RootController()), extra_environ=self.environ)
1159 r = app.get('/foo/')
1160 assert r.status_int == 200
1161
1162
1163 class TestRedirect(PecanTestCase):
1164
1165 @property
1166 def app_(self):
1167 class RootController(object):
1168 @expose()
1169 def index(self):
1170 redirect('/testing')
1171
1172 @expose()
1173 def internal(self):
1174 redirect('/testing', internal=True)
1175
1176 @expose()
1177 def bad_internal(self):
1178 redirect('/testing', internal=True, code=301)
1179
1180 @expose()
1181 def permanent(self):
1182 redirect('/testing', code=301)
1183
1184 @expose()
1185 def testing(self):
1186 return 'it worked!'
1187
1188 return TestApp(make_app(RootController(), debug=False))
1189
1190 def test_index(self):
1191 r = self.app_.get('/')
1192 assert r.status_int == 302
1193 r = r.follow()
1194 assert r.status_int == 200
1195 assert r.body == b'it worked!'
1196
1197 def test_internal(self):
1198 r = self.app_.get('/internal')
1199 assert r.status_int == 200
1200 assert r.body == b'it worked!'
1201
1202 def test_internal_with_301(self):
1203 self.assertRaises(ValueError, self.app_.get, '/bad_internal')
1204
1205 def test_permanent_redirect(self):
1206 r = self.app_.get('/permanent')
1207 assert r.status_int == 301
1208 r = r.follow()
1209 assert r.status_int == 200
1210 assert r.body == b'it worked!'
1211
1212 def test_x_forward_proto(self):
1213 class ChildController(object):
1214 @expose()
1215 def index(self):
1216 redirect('/testing') # pragma: nocover
1217
1218 class RootController(object):
1219 @expose()
1220 def index(self):
1221 redirect('/testing') # pragma: nocover
1222
1223 @expose()
1224 def testing(self):
1225 return 'it worked!' # pragma: nocover
1226 child = ChildController()
1227
1228 app = TestApp(make_app(RootController(), debug=True))
1229 res = app.get(
1230 '/child', extra_environ=dict(HTTP_X_FORWARDED_PROTO='https')
1231 )
1232 # non-canonical url will redirect, so we won't get a 301
1233 assert res.status_int == 302
1234 # should add trailing / and changes location to https
1235 assert res.location == 'https://localhost/child/'
1236 assert res.request.environ['HTTP_X_FORWARDED_PROTO'] == 'https'
1237
1238
1239 class TestInternalRedirectContext(PecanTestCase):
1240
1241 @property
1242 def app_(self):
1243 class RootController(object):
1244
1245 @expose()
1246 def redirect_with_context(self):
1247 request.context['foo'] = 'bar'
1248 redirect('/testing')
1249
1250 @expose()
1251 def internal_with_context(self):
1252 request.context['foo'] = 'bar'
1253 redirect('/testing', internal=True)
1254
1255 @expose('json')
1256 def testing(self):
1257 return request.context
1258
1259 return TestApp(make_app(RootController(), debug=False))
1260
1261 def test_internal_with_request_context(self):
1262 r = self.app_.get('/internal_with_context')
1263 assert r.status_int == 200
1264 assert json.loads(r.body.decode()) == {'foo': 'bar'}
1265
1266 def test_context_does_not_bleed(self):
1267 r = self.app_.get('/redirect_with_context').follow()
1268 assert r.status_int == 200
1269 assert json.loads(r.body.decode()) == {}
1270
1271
1272 class TestStreamedResponse(PecanTestCase):
1273
1274 def test_streaming_response(self):
1275
1276 class RootController(object):
1277 @expose(content_type='text/plain')
1278 def test(self, foo):
1279 if foo == 'stream':
1280 # mimic large file
1281 contents = BytesIO(b'stream')
1282 response.content_type = 'application/octet-stream'
1283 contents.seek(0, os.SEEK_END)
1284 response.content_length = contents.tell()
1285 contents.seek(0, os.SEEK_SET)
1286 response.app_iter = contents
1287 return response
1288 else:
1289 return 'plain text'
1290
1291 app = TestApp(Pecan(RootController()))
1292 r = app.get('/test/stream')
1293 assert r.content_type == 'application/octet-stream'
1294 assert r.body == b'stream'
1295
1296 r = app.get('/test/plain')
1297 assert r.content_type == 'text/plain'
1298 assert r.body == b'plain text'
1299
1300
1301 class TestManualResponse(PecanTestCase):
1302
1303 def test_manual_response(self):
1304
1305 class RootController(object):
1306 @expose()
1307 def index(self):
1308 resp = webob.Response(response.environ)
1309 resp.body = b'Hello, World!'
1310 return resp
1311
1312 app = TestApp(Pecan(RootController()))
1313 r = app.get('/')
1314 assert r.body == b'Hello, World!'
1315
1316
1317 class TestCustomResponseandRequest(PecanTestCase):
1318
1319 def test_custom_objects(self):
1320
1321 class CustomRequest(Request):
1322
1323 @property
1324 def headers(self):
1325 headers = super(CustomRequest, self).headers
1326 headers['X-Custom-Request'] = 'ABC'
1327 return headers
1328
1329 class CustomResponse(Response):
1330
1331 @property
1332 def headers(self):
1333 headers = super(CustomResponse, self).headers
1334 headers['X-Custom-Response'] = 'XYZ'
1335 return headers
1336
1337 class RootController(object):
1338 @expose()
1339 def index(self):
1340 return request.headers.get('X-Custom-Request')
1341
1342 app = TestApp(Pecan(
1343 RootController(),
1344 request_cls=CustomRequest,
1345 response_cls=CustomResponse
1346 ))
1347 r = app.get('/')
1348 assert r.body == b'ABC'
1349 assert r.headers.get('X-Custom-Response') == 'XYZ'
1350
1351
1352 class TestThreadLocalState(PecanTestCase):
1353
1354 def test_thread_local_dir(self):
1355 """
1356 Threadlocal proxies for request and response should properly
1357 proxy ``dir()`` calls to the underlying webob class.
1358 """
1359 class RootController(object):
1360 @expose()
1361 def index(self):
1362 assert 'method' in dir(request)
1363 assert 'status' in dir(response)
1364 return '/'
1365
1366 app = TestApp(Pecan(RootController()))
1367 r = app.get('/')
1368 assert r.status_int == 200
1369 assert r.body == b'/'
1370
1371 def test_request_state_cleanup(self):
1372 """
1373 After a request, the state local() should be totally clean
1374 except for state.app (so that objects don't leak between requests)
1375 """
1376 from pecan.core import state
1377
1378 class RootController(object):
1379 @expose()
1380 def index(self):
1381 return '/'
1382
1383 app = TestApp(Pecan(RootController()))
1384 r = app.get('/')
1385 assert r.status_int == 200
1386 assert r.body == b'/'
1387
1388 assert state.__dict__ == {}
1389
1390
1391 class TestFileTypeExtensions(PecanTestCase):
1392
1393 @property
1394 def app_(self):
1395 """
1396 Test extension splits
1397 """
1398 class RootController(object):
1399 @expose(content_type=None)
1400 def _default(self, *args):
1401 ext = request.pecan['extension']
1402 assert len(args) == 1
1403 if ext:
1404 assert ext not in args[0]
1405 return ext or ''
1406
1407 return TestApp(Pecan(RootController()))
1408
1409 def test_html_extension(self):
1410 for path in ('/index.html', '/index.html/'):
1411 r = self.app_.get(path)
1412 assert r.status_int == 200
1413 assert r.body == b'.html'
1414
1415 def test_image_extension(self):
1416 for path in ('/index.png', '/index.png/'):
1417 r = self.app_.get(path)
1418 assert r.status_int == 200
1419 assert r.body == b'.png'
1420
1421 def test_hidden_file(self):
1422 for path in ('/.vimrc', '/.vimrc/'):
1423 r = self.app_.get(path)
1424 assert r.status_int == 204
1425 assert r.body == b''
1426
1427 def test_multi_dot_extension(self):
1428 for path in ('/gradient.min.js', '/gradient.min.js/'):
1429 r = self.app_.get(path)
1430 assert r.status_int == 200
1431 assert r.body == b'.js'
1432
1433 def test_bad_content_type(self):
1434 class RootController(object):
1435 @expose()
1436 def index(self):
1437 return '/'
1438
1439 app = TestApp(Pecan(RootController()))
1440 r = app.get('/')
1441 assert r.status_int == 200
1442 assert r.body == b'/'
1443
1444 r = app.get('/index.html', expect_errors=True)
1445 assert r.status_int == 200
1446 assert r.body == b'/'
1447
1448 with warnings.catch_warnings():
1449 warnings.simplefilter("ignore")
1450 r = app.get('/index.txt', expect_errors=True)
1451 assert r.status_int == 404
1452
1453 def test_unknown_file_extension(self):
1454 class RootController(object):
1455 @expose(content_type=None)
1456 def _default(self, *args):
1457 assert 'example:x.tiny' in args
1458 assert request.pecan['extension'] is None
1459 return 'SOME VALUE'
1460
1461 app = TestApp(Pecan(RootController()))
1462
1463 r = app.get('/example:x.tiny')
1464 assert r.status_int == 200
1465 assert r.body == b'SOME VALUE'
1466
1467 def test_guessing_disabled(self):
1468 class RootController(object):
1469 @expose(content_type=None)
1470 def _default(self, *args):
1471 assert 'index.html' in args
1472 assert request.pecan['extension'] is None
1473 return 'SOME VALUE'
1474
1475 app = TestApp(Pecan(RootController(),
1476 guess_content_type_from_ext=False))
1477
1478 r = app.get('/index.html')
1479 assert r.status_int == 200
1480 assert r.body == b'SOME VALUE'
1481
1482 def test_content_type_guessing_disabled(self):
1483
1484 class ResourceController(object):
1485
1486 def __init__(self, name):
1487 self.name = name
1488 assert self.name == 'file.html'
1489
1490 @expose('json')
1491 def index(self):
1492 return dict(name=self.name)
1493
1494 class RootController(object):
1495
1496 @expose()
1497 def _lookup(self, name, *remainder):
1498 return ResourceController(name), remainder
1499
1500 app = TestApp(
1501 Pecan(RootController(), guess_content_type_from_ext=False)
1502 )
1503
1504 r = app.get('/file.html/')
1505 assert r.status_int == 200
1506 result = dict(json.loads(r.body.decode()))
1507 assert result == {'name': 'file.html'}
1508
1509 r = app.get('/file.html')
1510 assert r.status_int == 302
1511 r = r.follow()
1512 result = dict(json.loads(r.body.decode()))
1513 assert result == {'name': 'file.html'}
1514
1515
1516 class TestContentTypeByAcceptHeaders(PecanTestCase):
1517
1518 @property
1519 def app_(self):
1520 """
1521 Test that content type is set appropriately based on Accept headers.
1522 """
1523 class RootController(object):
1524
1525 @expose(content_type='text/html')
1526 @expose(content_type='application/json')
1527 def index(self, *args):
1528 return 'Foo'
1529
1530 return TestApp(Pecan(RootController()))
1531
1532 def test_missing_accept(self):
1533 r = self.app_.get('/', headers={
1534 'Accept': ''
1535 })
1536 assert r.status_int == 200
1537 assert r.content_type == 'text/html'
1538
1539 def test_quality(self):
1540 r = self.app_.get('/', headers={
1541 'Accept': 'text/html,application/json;q=0.9,*/*;q=0.8'
1542 })
1543 assert r.status_int == 200
1544 assert r.content_type == 'text/html'
1545
1546 r = self.app_.get('/', headers={
1547 'Accept': 'application/json,text/html;q=0.9,*/*;q=0.8'
1548 })
1549 assert r.status_int == 200
1550 assert r.content_type == 'application/json'
1551
1552 def test_discarded_accept_parameters(self):
1553 r = self.app_.get('/', headers={
1554 'Accept': 'application/json;discard=me'
1555 })
1556 assert r.status_int == 200
1557 assert r.content_type == 'application/json'
1558
1559 def test_file_extension_has_higher_precedence(self):
1560 r = self.app_.get('/index.html', headers={
1561 'Accept': 'application/json,text/html;q=0.9,*/*;q=0.8'
1562 })
1563 assert r.status_int == 200
1564 assert r.content_type == 'text/html'
1565
1566 def test_not_acceptable(self):
1567 r = self.app_.get('/', headers={
1568 'Accept': 'application/xml',
1569 }, status=406)
1570 assert r.status_int == 406
1571
1572 def test_accept_header_missing(self):
1573 r = self.app_.get('/')
1574 assert r.status_int == 200
1575 assert r.content_type == 'text/html'
1576
1577
1578 class TestCanonicalRouting(PecanTestCase):
1579
1580 @property
1581 def app_(self):
1582 class ArgSubController(object):
1583 @expose()
1584 def index(self, arg):
1585 return arg
1586
1587 class AcceptController(object):
1588 @accept_noncanonical
1589 @expose()
1590 def index(self):
1591 return 'accept'
1592
1593 class SubController(object):
1594 @expose()
1595 def index(self, **kw):
1596 return 'subindex'
1597
1598 class RootController(object):
1599 @expose()
1600 def index(self):
1601 return 'index'
1602
1603 sub = SubController()
1604 arg = ArgSubController()
1605 accept = AcceptController()
1606
1607 return TestApp(Pecan(RootController()))
1608
1609 def test_root(self):
1610 r = self.app_.get('/')
1611 assert r.status_int == 200
1612 assert b'index' in r.body
1613
1614 def test_index(self):
1615 r = self.app_.get('/index')
1616 assert r.status_int == 200
1617 assert b'index' in r.body
1618
1619 def test_broken_clients(self):
1620 # for broken clients
1621 r = self.app_.get('', status=302)
1622 assert r.status_int == 302
1623 assert r.location == 'http://localhost/'
1624
1625 def test_sub_controller_with_trailing(self):
1626 r = self.app_.get('/sub/')
1627 assert r.status_int == 200
1628 assert b'subindex' in r.body
1629
1630 def test_sub_controller_redirect(self):
1631 r = self.app_.get('/sub', status=302)
1632 assert r.status_int == 302
1633 assert r.location == 'http://localhost/sub/'
1634
1635 def test_with_query_string(self):
1636 # try with query string
1637 r = self.app_.get('/sub?foo=bar', status=302)
1638 assert r.status_int == 302
1639 assert r.location == 'http://localhost/sub/?foo=bar'
1640
1641 def test_posts_fail(self):
1642 try:
1643 self.app_.post('/sub', dict(foo=1))
1644 raise Exception("Post should fail") # pragma: nocover
1645 except Exception as e:
1646 assert isinstance(e, RuntimeError)
1647
1648 def test_with_args(self):
1649 r = self.app_.get('/arg/index/foo')
1650 assert r.status_int == 200
1651 assert r.body == b'foo'
1652
1653 def test_accept_noncanonical(self):
1654 r = self.app_.get('/accept/')
1655 assert r.status_int == 200
1656 assert r.body == b'accept'
1657
1658 def test_accept_noncanonical_no_trailing_slash(self):
1659 r = self.app_.get('/accept')
1660 assert r.status_int == 200
1661 assert r.body == b'accept'
1662
1663
1664 class TestNonCanonical(PecanTestCase):
1665
1666 @property
1667 def app_(self):
1668 class ArgSubController(object):
1669 @expose()
1670 def index(self, arg):
1671 return arg # pragma: nocover
1672
1673 class AcceptController(object):
1674 @accept_noncanonical
1675 @expose()
1676 def index(self):
1677 return 'accept' # pragma: nocover
1678
1679 class SubController(object):
1680 @expose()
1681 def index(self, **kw):
1682 return 'subindex'
1683
1684 class RootController(object):
1685 @expose()
1686 def index(self):
1687 return 'index'
1688
1689 sub = SubController()
1690 arg = ArgSubController()
1691 accept = AcceptController()
1692
1693 return TestApp(Pecan(RootController(), force_canonical=False))
1694
1695 def test_index(self):
1696 r = self.app_.get('/')
1697 assert r.status_int == 200
1698 assert b'index' in r.body
1699
1700 def test_subcontroller(self):
1701 r = self.app_.get('/sub')
1702 assert r.status_int == 200
1703 assert b'subindex' in r.body
1704
1705 def test_subcontroller_with_kwargs(self):
1706 r = self.app_.post('/sub', dict(foo=1))
1707 assert r.status_int == 200
1708 assert b'subindex' in r.body
1709
1710 def test_sub_controller_with_trailing(self):
1711 r = self.app_.get('/sub/')
1712 assert r.status_int == 200
1713 assert b'subindex' in r.body
1714
1715 def test_proxy(self):
1716 class RootController(object):
1717 @expose()
1718 def index(self):
1719 request.testing = True
1720 assert request.testing is True
1721 del request.testing
1722 assert hasattr(request, 'testing') is False
1723 return '/'
1724
1725 app = TestApp(make_app(RootController(), debug=True))
1726 r = app.get('/')
1727 assert r.status_int == 200
1728
1729 def test_app_wrap(self):
1730 class RootController(object):
1731 pass
1732
1733 wrapped_apps = []
1734
1735 def wrap(app):
1736 wrapped_apps.append(app)
1737 return app
1738
1739 make_app(RootController(), wrap_app=wrap, debug=True)
1740 assert len(wrapped_apps) == 1
1741
1742
1743 class TestLogging(PecanTestCase):
1744
1745 def test_logging_setup(self):
1746 class RootController(object):
1747 @expose()
1748 def index(self):
1749 import logging
1750 logging.getLogger('pecantesting').info('HELLO WORLD')
1751 return "HELLO WORLD"
1752
1753 f = StringIO()
1754
1755 app = TestApp(make_app(RootController(), logging={
1756 'loggers': {
1757 'pecantesting': {
1758 'level': 'INFO', 'handlers': ['memory']
1759 }
1760 },
1761 'handlers': {
1762 'memory': {
1763 'level': 'INFO',
1764 'class': 'logging.StreamHandler',
1765 'stream': f
1766 }
1767 }
1768 }))
1769
1770 app.get('/')
1771 assert f.getvalue() == 'HELLO WORLD\n'
1772
1773 def test_logging_setup_with_config_obj(self):
1774 class RootController(object):
1775 @expose()
1776 def index(self):
1777 import logging
1778 logging.getLogger('pecantesting').info('HELLO WORLD')
1779 return "HELLO WORLD"
1780
1781 f = StringIO()
1782
1783 from pecan.configuration import conf_from_dict
1784 app = TestApp(make_app(RootController(), logging=conf_from_dict({
1785 'loggers': {
1786 'pecantesting': {
1787 'level': 'INFO', 'handlers': ['memory']
1788 }
1789 },
1790 'handlers': {
1791 'memory': {
1792 'level': 'INFO',
1793 'class': 'logging.StreamHandler',
1794 'stream': f
1795 }
1796 }
1797 })))
1798
1799 app.get('/')
1800 assert f.getvalue() == 'HELLO WORLD\n'
1801
1802
1803 class TestEngines(PecanTestCase):
1804
1805 template_path = os.path.join(os.path.dirname(__file__), 'templates')
1806
1807 @unittest.skipIf('genshi' not in builtin_renderers, 'Genshi not installed')
1808 def test_genshi(self):
1809
1810 class RootController(object):
1811 @expose('genshi:genshi.html')
1812 def index(self, name='Jonathan'):
1813 return dict(name=name)
1814
1815 @expose('genshi:genshi_bad.html')
1816 def badtemplate(self):
1817 return dict()
1818
1819 app = TestApp(
1820 Pecan(RootController(), template_path=self.template_path)
1821 )
1822 r = app.get('/')
1823 assert r.status_int == 200
1824 assert b"<h1>Hello, Jonathan!</h1>" in r.body
1825
1826 r = app.get('/index.html?name=World')
1827 assert r.status_int == 200
1828 assert b"<h1>Hello, World!</h1>" in r.body
1829
1830 error_msg = None
1831 try:
1832 r = app.get('/badtemplate.html')
1833 except Exception as e:
1834 for error_f in error_formatters:
1835 error_msg = error_f(e)
1836 if error_msg:
1837 break
1838 assert error_msg is not None
1839
1840 @unittest.skipIf('kajiki' not in builtin_renderers, 'Kajiki not installed')
1841 def test_kajiki(self):
1842
1843 class RootController(object):
1844 @expose('kajiki:kajiki.html')
1845 def index(self, name='Jonathan'):
1846 return dict(name=name)
1847
1848 app = TestApp(
1849 Pecan(RootController(), template_path=self.template_path)
1850 )
1851 r = app.get('/')
1852 assert r.status_int == 200
1853 assert b"<h1>Hello, Jonathan!</h1>" in r.body
1854
1855 r = app.get('/index.html?name=World')
1856 assert r.status_int == 200
1857 assert b"<h1>Hello, World!</h1>" in r.body
1858
1859 @unittest.skipIf('jinja' not in builtin_renderers, 'Jinja not installed')
1860 def test_jinja(self):
1861
1862 class RootController(object):
1863 @expose('jinja:jinja.html')
1864 def index(self, name='Jonathan'):
1865 return dict(name=name)
1866
1867 @expose('jinja:jinja_bad.html')
1868 def badtemplate(self):
1869 return dict()
1870
1871 app = TestApp(
1872 Pecan(RootController(), template_path=self.template_path)
1873 )
1874 r = app.get('/')
1875 assert r.status_int == 200
1876 assert b"<h1>Hello, Jonathan!</h1>" in r.body
1877
1878 error_msg = None
1879 try:
1880 r = app.get('/badtemplate.html')
1881 except Exception as e:
1882 for error_f in error_formatters:
1883 error_msg = error_f(e)
1884 if error_msg:
1885 break
1886 assert error_msg is not None
1887
1888 @unittest.skipIf('mako' not in builtin_renderers, 'Mako not installed')
1889 def test_mako(self):
1890
1891 class RootController(object):
1892 @expose('mako:mako.html')
1893 def index(self, name='Jonathan'):
1894 return dict(name=name)
1895
1896 @expose('mako:mako_bad.html')
1897 def badtemplate(self):
1898 return dict()
1899
1900 app = TestApp(
1901 Pecan(RootController(), template_path=self.template_path)
1902 )
1903 r = app.get('/')
1904 assert r.status_int == 200
1905 assert b"<h1>Hello, Jonathan!</h1>" in r.body
1906
1907 r = app.get('/index.html?name=World')
1908 assert r.status_int == 200
1909 assert b"<h1>Hello, World!</h1>" in r.body
1910
1911 error_msg = None
1912 try:
1913 r = app.get('/badtemplate.html')
1914 except Exception as e:
1915 for error_f in error_formatters:
1916 error_msg = error_f(e)
1917 if error_msg:
1918 break
1919 assert error_msg is not None
1920
1921 def test_renderer_not_found(self):
1922
1923 class RootController(object):
1924 @expose('mako3:mako.html')
1925 def index(self, name='Jonathan'):
1926 return dict(name=name)
1927
1928 app = TestApp(
1929 Pecan(RootController(), template_path=self.template_path)
1930 )
1931 try:
1932 r = app.get('/')
1933 except Exception as e:
1934 expected = e
1935
1936 assert 'support for "mako3" was not found;' in str(expected)
1937
1938 def test_json(self):
1939 expected_result = dict(
1940 name='Jonathan',
1941 age=30, nested=dict(works=True)
1942 )
1943
1944 class RootController(object):
1945 @expose('json')
1946 def index(self):
1947 return expected_result
1948
1949 app = TestApp(Pecan(RootController()))
1950 r = app.get('/')
1951 assert r.status_int == 200
1952 result = json.loads(r.body.decode())
1953 assert result == expected_result
1954
1955 def test_custom_renderer(self):
1956
1957 class RootController(object):
1958 @expose('backwards:mako.html')
1959 def index(self, name='Joe'):
1960 return dict(name=name)
1961
1962 class BackwardsRenderer(MakoRenderer):
1963 # Custom renderer that reverses all string namespace values
1964 def render(self, template_path, namespace):
1965 namespace = dict(
1966 (k, v[::-1])
1967 for k, v in namespace.items()
1968 )
1969 return super(BackwardsRenderer, self).render(template_path,
1970 namespace)
1971
1972 app = TestApp(Pecan(
1973 RootController(),
1974 template_path=self.template_path,
1975 custom_renderers={'backwards': BackwardsRenderer}
1976 ))
1977 r = app.get('/')
1978 assert r.status_int == 200
1979 assert b"<h1>Hello, eoJ!</h1>" in r.body
1980
1981 r = app.get('/index.html?name=Tim')
1982 assert r.status_int == 200
1983 assert b"<h1>Hello, miT!</h1>" in r.body
1984
1985 def test_override_template(self):
1986 class RootController(object):
1987 @expose('foo.html')
1988 def index(self):
1989 override_template(None, content_type='text/plain')
1990 return 'Override'
1991
1992 app = TestApp(Pecan(RootController()))
1993 r = app.get('/')
1994 assert r.status_int == 200
1995 assert b'Override' in r.body
1996 assert r.content_type == 'text/plain'
1997
1998 def test_render(self):
1999 class RootController(object):
2000 @expose()
2001 def index(self, name='Jonathan'):
2002 return render('mako.html', dict(name=name))
2003
2004 app = TestApp(
2005 Pecan(RootController(), template_path=self.template_path)
2006 )
2007 r = app.get('/')
2008 assert r.status_int == 200
2009 assert b"<h1>Hello, Jonathan!</h1>" in r.body
2010
2011 def test_default_json_renderer(self):
2012
2013 class RootController(object):
2014 @expose()
2015 def index(self, name='Bill'):
2016 return dict(name=name)
2017
2018 app = TestApp(Pecan(RootController(), default_renderer='json'))
2019 r = app.get('/')
2020 assert r.status_int == 200
2021 result = dict(json.loads(r.body.decode()))
2022 assert result == {'name': 'Bill'}
2023
2024 def test_default_json_renderer_with_explicit_content_type(self):
2025
2026 class RootController(object):
2027 @expose(content_type='text/plain')
2028 def index(self, name='Bill'):
2029 return name
2030
2031 app = TestApp(Pecan(RootController(), default_renderer='json'))
2032 r = app.get('/')
2033 assert r.status_int == 200
2034 assert r.body == b"Bill"
2035
2036
2037 class TestDeprecatedRouteMethod(PecanTestCase):
2038
2039 @property
2040 def app_(self):
2041 class RootController(object):
2042
2043 @expose()
2044 def index(self, *args):
2045 return ', '.join(args)
2046
2047 @expose()
2048 def _route(self, args):
2049 return self.index, args
2050
2051 return TestApp(Pecan(RootController()))
2052
2053 def test_required_argument(self):
2054 with warnings.catch_warnings():
2055 warnings.simplefilter("ignore")
2056 r = self.app_.get('/foo/bar/')
2057 assert r.status_int == 200
2058 assert b'foo, bar' in r.body
2059
2060
2061 class TestExplicitRoute(PecanTestCase):
2062
2063 def test_alternate_route(self):
2064
2065 class RootController(object):
2066
2067 @expose(route='some-path')
2068 def some_path(self):
2069 return 'Hello, World!'
2070
2071 app = TestApp(Pecan(RootController()))
2072
2073 r = app.get('/some-path/')
2074 assert r.status_int == 200
2075 assert r.body == b'Hello, World!'
2076
2077 r = app.get('/some_path/', expect_errors=True)
2078 assert r.status_int == 404
2079
2080 def test_manual_route(self):
2081
2082 class SubController(object):
2083
2084 @expose(route='some-path')
2085 def some_path(self):
2086 return 'Hello, World!'
2087
2088 class RootController(object):
2089 pass
2090
2091 route(RootController, 'some-controller', SubController())
2092
2093 app = TestApp(Pecan(RootController()))
2094
2095 r = app.get('/some-controller/some-path/')
2096 assert r.status_int == 200
2097 assert r.body == b'Hello, World!'
2098
2099 r = app.get('/some-controller/some_path/', expect_errors=True)
2100 assert r.status_int == 404
2101
2102 def test_manual_route_conflict(self):
2103
2104 class SubController(object):
2105 pass
2106
2107 class RootController(object):
2108
2109 @expose()
2110 def hello(self):
2111 return 'Hello, World!'
2112
2113 self.assertRaises(
2114 RuntimeError,
2115 route,
2116 RootController,
2117 'hello',
2118 SubController()
2119 )
2120
2121 def test_custom_route_on_index(self):
2122
2123 class RootController(object):
2124
2125 @expose(route='some-path')
2126 def index(self):
2127 return 'Hello, World!'
2128
2129 app = TestApp(Pecan(RootController()))
2130
2131 r = app.get('/some-path/')
2132 assert r.status_int == 200
2133 assert r.body == b'Hello, World!'
2134
2135 r = app.get('/')
2136 assert r.status_int == 200
2137 assert r.body == b'Hello, World!'
2138
2139 r = app.get('/index/', expect_errors=True)
2140 assert r.status_int == 404
2141
2142 def test_custom_route_with_attribute_conflict(self):
2143
2144 class RootController(object):
2145
2146 @expose(route='mock')
2147 def greet(self):
2148 return 'Hello, World!'
2149
2150 @expose()
2151 def mock(self):
2152 return 'You are not worthy!'
2153
2154 app = TestApp(Pecan(RootController()))
2155
2156 self.assertRaises(
2157 RuntimeError,
2158 app.get,
2159 '/mock/'
2160 )
2161
2162 def test_conflicting_custom_routes(self):
2163
2164 class RootController(object):
2165
2166 @expose(route='testing')
2167 def foo(self):
2168 return 'Foo!'
2169
2170 @expose(route='testing')
2171 def bar(self):
2172 return 'Bar!'
2173
2174 app = TestApp(Pecan(RootController()))
2175
2176 self.assertRaises(
2177 RuntimeError,
2178 app.get,
2179 '/testing/'
2180 )
2181
2182 def test_conflicting_custom_routes_in_subclass(self):
2183
2184 class BaseController(object):
2185
2186 @expose(route='testing')
2187 def foo(self):
2188 return request.path
2189
2190 class ChildController(BaseController):
2191 pass
2192
2193 class RootController(BaseController):
2194 child = ChildController()
2195
2196 app = TestApp(Pecan(RootController()))
2197
2198 r = app.get('/testing/')
2199 assert r.body == b'/testing/'
2200
2201 r = app.get('/child/testing/')
2202 assert r.body == b'/child/testing/'
2203
2204 def test_custom_route_prohibited_on_lookup(self):
2205 try:
2206 class RootController(object):
2207
2208 @expose(route='some-path')
2209 def _lookup(self):
2210 return 'Hello, World!'
2211 except ValueError:
2212 pass
2213 else:
2214 raise AssertionError(
2215 '_lookup cannot be used with a custom path segment'
2216 )
2217
2218 def test_custom_route_prohibited_on_default(self):
2219 try:
2220 class RootController(object):
2221
2222 @expose(route='some-path')
2223 def _default(self):
2224 return 'Hello, World!'
2225 except ValueError:
2226 pass
2227 else:
2228 raise AssertionError(
2229 '_default cannot be used with a custom path segment'
2230 )
2231
2232 def test_custom_route_prohibited_on_route(self):
2233 try:
2234 class RootController(object):
2235
2236 @expose(route='some-path')
2237 def _route(self):
2238 return 'Hello, World!'
2239 except ValueError:
2240 pass
2241 else:
2242 raise AssertionError(
2243 '_route cannot be used with a custom path segment'
2244 )
2245
2246 def test_custom_route_with_generic_controllers(self):
2247
2248 class RootController(object):
2249
2250 @expose(route='some-path', generic=True)
2251 def foo(self):
2252 return 'Hello, World!'
2253
2254 @foo.when(method='POST')
2255 def handle_post(self):
2256 return 'POST!'
2257
2258 app = TestApp(Pecan(RootController()))
2259
2260 r = app.get('/some-path/')
2261 assert r.status_int == 200
2262 assert r.body == b'Hello, World!'
2263
2264 r = app.get('/foo/', expect_errors=True)
2265 assert r.status_int == 404
2266
2267 r = app.post('/some-path/')
2268 assert r.status_int == 200
2269 assert r.body == b'POST!'
2270
2271 r = app.post('/foo/', expect_errors=True)
2272 assert r.status_int == 404
2273
2274 def test_custom_route_prohibited_on_generic_controllers(self):
2275 try:
2276 class RootController(object):
2277
2278 @expose(generic=True)
2279 def foo(self):
2280 return 'Hello, World!'
2281
2282 @foo.when(method='POST', route='some-path')
2283 def handle_post(self):
2284 return 'POST!'
2285 except ValueError:
2286 pass
2287 else:
2288 raise AssertionError(
2289 'generic controllers cannot be used with a custom path segment'
2290 )
2291
2292 def test_invalid_route_arguments(self):
2293 class C(object):
2294
2295 def secret(self):
2296 return {}
2297
2298 self.assertRaises(TypeError, route)
2299 self.assertRaises(TypeError, route, 'some-path', lambda x: x)
2300 self.assertRaises(TypeError, route, 'some-path', C.secret)
2301 self.assertRaises(TypeError, route, C, {}, C())
2302
2303 for path in (
2304 'VARIED-case-PATH',
2305 'this,custom,path',
2306 '123-path',
2307 'path(with-parens)',
2308 'path;with;semicolons',
2309 'path:with:colons',
2310 'v2.0',
2311 '~username',
2312 'somepath!',
2313 'four*four',
2314 'one+two',
2315 '@twitterhandle',
2316 'package=pecan'
2317 ):
2318 handler = C()
2319 route(C, path, handler)
2320 assert getattr(C, path, handler)
2321
2322 self.assertRaises(ValueError, route, C, '/path/', C())
2323 self.assertRaises(ValueError, route, C, '.', C())
2324 self.assertRaises(ValueError, route, C, '..', C())
2325 self.assertRaises(ValueError, route, C, 'path?', C())
2326 self.assertRaises(ValueError, route, C, 'percent%20encoded', C())