File: test_application.py

package info (click to toggle)
webpy 1%3A0.62-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 640 kB
  • sloc: python: 6,880; makefile: 153; sh: 1
file content (437 lines) | stat: -rw-r--r-- 11,947 bytes parent folder | download | duplicates (3)
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import os
import shutil
import sys
import threading
import time
import unittest

import web

try:
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlencode

data = """
import web

urls = ("/", "%(classname)s")
app = web.application(urls, globals(), autoreload=True)

class %(classname)s:
    def GET(self):
        return "%(output)s"

"""

urls = ("/iter", "do_iter")
app = web.application(urls, globals())


class do_iter:
    def GET(self):
        yield "hello, "
        yield web.input(name="world").name

    POST = GET


def write(filename, data):
    f = open(filename, "w")
    f.write(data)
    f.close()


class ApplicationTest(unittest.TestCase):
    def test_reloader(self):
        write("foo.py", data % dict(classname="a", output="a"))
        import foo

        app = foo.app

        self.assertEqual(app.request("/").data, b"a")

        # test class change
        time.sleep(1)
        write("foo.py", data % dict(classname="a", output="b"))
        self.assertEqual(app.request("/").data, b"b")

        # test urls change
        time.sleep(1)
        write("foo.py", data % dict(classname="c", output="c"))
        self.assertEqual(app.request("/").data, b"c")

    def test_reloader_nested(self):
        try:
            shutil.rmtree("testpackage")
        except OSError:
            pass
        os.mkdir("testpackage")
        write("testpackage/__init__.py", "")
        write("testpackage/bar.py", data % dict(classname="a", output="a"))
        import testpackage.bar

        app = testpackage.bar.app

        self.assertEqual(app.request("/").data, b"a")

        # test class change
        time.sleep(1)
        write("testpackage/bar.py", data % dict(classname="a", output="b"))
        self.assertEqual(app.request("/").data, b"b")

        # test urls change
        time.sleep(1)
        write("testpackage/bar.py", data % dict(classname="c", output="c"))
        self.assertEqual(app.request("/").data, b"c")

    def testUppercaseMethods(self):
        urls = ("/", "hello")
        app = web.application(urls, locals())

        class hello:
            def GET(self):
                return "hello"

            def internal(self):
                return "secret"

        response = app.request("/", method="internal")
        self.assertEqual(response.status, "405 Method Not Allowed")

    def testRedirect(self):
        # fmt: off
        urls = (
            "/a", "redirect /hello/",
            "/b/(.*)", r"redirect /hello/\1",
            "/hello/(.*)", "hello"
        )
        # fmt: on

        app = web.application(urls, locals())

        class hello:
            def GET(self, name):
                name = name or "world"
                return "hello " + name

        response = app.request("/a")
        self.assertEqual(response.status, "301 Moved Permanently")
        self.assertEqual(response.headers["Location"], "http://0.0.0.0:8080/hello/")

        response = app.request("/a?x=2")
        self.assertEqual(response.status, "301 Moved Permanently")
        self.assertEqual(response.headers["Location"], "http://0.0.0.0:8080/hello/?x=2")

        response = app.request("/b/foo?x=2")
        self.assertEqual(response.status, "301 Moved Permanently")
        self.assertEqual(
            response.headers["Location"], "http://0.0.0.0:8080/hello/foo?x=2"
        )

    def test_routing(self):
        urls = ("/foo", "foo")

        class foo:
            def GET(self):
                return "foo"

        app = web.application(urls, {"foo": foo})

        self.assertEqual(app.request("/foo\n").data, b"not found")
        self.assertEqual(app.request("/foo").data, b"foo")

    def test_subdirs(self):
        urls = ("/(.*)", "blog")

        class blog:
            def GET(self, path):
                return "blog " + path

        app_blog = web.application(urls, locals())

        # fmt: off
        urls = (
            "/blog", app_blog,
            "/(.*)", "index"
        )
        # fmt: on

        class index:
            def GET(self, path):
                return "hello " + path

        app = web.application(urls, locals())

        self.assertEqual(app.request("/blog/foo").data, b"blog foo")
        self.assertEqual(app.request("/foo").data, b"hello foo")

        def processor(handler):
            return web.ctx.path + ":" + handler()

        app.add_processor(processor)
        self.assertEqual(app.request("/blog/foo").data, b"/blog/foo:blog foo")

    def test_subdomains(self):
        def create_app(name):
            urls = ("/", "index")

            class index:
                def GET(self):
                    return name

            return web.application(urls, locals())

        # fmt: off
        urls = (
            "a.example.com", create_app('a'),
            "b.example.com", create_app('b'),
            ".*.example.com", create_app('*')
        )
        # fmt: on

        app = web.subdomain_application(urls, locals())

        def test(host, expected_result):
            result = app.request("/", host=host)
            self.assertEqual(result.data, expected_result)

        test("a.example.com", b"a")
        test("b.example.com", b"b")
        test("c.example.com", b"*")
        test("d.example.com", b"*")

    def test_redirect(self):
        urls = ("/(.*)", "blog")

        class blog:
            def GET(self, path):
                if path == "foo":
                    raise web.seeother("/login", absolute=True)
                else:
                    raise web.seeother("/bar")

        app_blog = web.application(urls, locals())

        # fmt: off
        urls = (
            "/blog", app_blog,
            "/(.*)", "index"
        )
        # fmt: on

        class index:
            def GET(self, path):
                return "hello " + path

        app = web.application(urls, locals())

        response = app.request("/blog/foo")
        self.assertEqual(response.headers["Location"], "http://0.0.0.0:8080/login")

        response = app.request("/blog/foo", env={"SCRIPT_NAME": "/x"})
        self.assertEqual(response.headers["Location"], "http://0.0.0.0:8080/x/login")

        response = app.request("/blog/foo2")
        self.assertEqual(response.headers["Location"], "http://0.0.0.0:8080/blog/bar")

        response = app.request("/blog/foo2", env={"SCRIPT_NAME": "/x"})
        self.assertEqual(response.headers["Location"], "http://0.0.0.0:8080/x/blog/bar")

    def test_processors(self):
        urls = ("/(.*)", "blog")

        class blog:
            def GET(self, path):
                return "blog " + path

        state = web.storage(x=0, y=0)

        def f():
            state.x += 1

        app_blog = web.application(urls, locals())
        app_blog.add_processor(web.loadhook(f))

        # fmt: off
        urls = (
            "/blog", app_blog,
            "/(.*)", "index"
        )
        # fmt: on

        class index:
            def GET(self, path):
                return "hello " + path

        app = web.application(urls, locals())

        def g():
            state.y += 1

        app.add_processor(web.loadhook(g))

        app.request("/blog/foo")
        assert state.x == 1 and state.y == 1, repr(state)
        app.request("/foo")
        assert state.x == 1 and state.y == 2, repr(state)

    def testUnicodeInput(self):
        urls = ("(/.*)", "foo")

        class foo:
            def GET(self, path):
                i = web.input(name="")
                return repr(i.name)

            def POST(self, path):
                if path == "/multipart":
                    i = web.input(file={})
                    return i.file.value
                else:
                    i = web.input()
                    return repr(dict(i)).replace("u", "")

        app = web.application(urls, locals())

        def f(name):
            path = "/?" + urlencode({"name": name.encode("utf-8")})
            self.assertEqual(app.request(path).data.decode("utf-8"), repr(name))

        f(u"\u1234")
        f(u"foo")

        response = app.request("/", method="POST", data=dict(name="foo"))

        self.assertEqual(response.data, b"{'name': 'foo'}")

        data = '--boundary\r\nContent-Disposition: form-data; name="x"\r\n\r\nfoo\r\n--boundary\r\nContent-Disposition: form-data; name="file"; filename="a.txt"\r\nContent-Type: text/plain\r\n\r\na\r\n--boundary--\r\n'
        headers = {"Content-Type": "multipart/form-data; boundary=boundary"}
        response = app.request("/multipart", method="POST", data=data, headers=headers)

        self.assertEqual(response.data, b"a")

    def testCustomNotFound(self):
        urls_a = ("/", "a")
        urls_b = ("/", "b")

        app_a = web.application(urls_a, locals())
        app_b = web.application(urls_b, locals())

        app_a.notfound = lambda: web.HTTPError("404 Not Found", {}, "not found 1")

        # fmt: off
        urls = (
            "/a", app_a,
            "/b", app_b
        )
        # fmt: on

        app = web.application(urls, locals())

        def assert_notfound(path, message):
            response = app.request(path)
            self.assertEqual(response.status.split()[0], "404")
            self.assertEqual(response.data, message)

        assert_notfound("/a/foo", b"not found 1")
        assert_notfound("/b/foo", b"not found")

        app.notfound = lambda: web.HTTPError("404 Not Found", {}, "not found 2")
        assert_notfound("/a/foo", b"not found 1")
        assert_notfound("/b/foo", b"not found 2")

    def testIter(self):
        self.assertEqual(app.request("/iter").data, b"hello, world")
        self.assertEqual(app.request("/iter?name=web").data, b"hello, web")

        self.assertEqual(app.request("/iter", method="POST").data, b"hello, world")
        self.assertEqual(
            app.request("/iter", method="POST", data="name=web").data, b"hello, web"
        )

    def testUnload(self):
        x = web.storage(a=0)

        # fmt: off
        urls = (
            "/foo", "foo",
            "/bar", "bar"
        )
        # fmt: on

        class foo:
            def GET(self):
                return "foo"

        class bar:
            def GET(self):
                raise web.notfound()

        app = web.application(urls, locals())

        def unload():
            x.a += 1

        app.add_processor(web.unloadhook(unload))

        app.request("/foo")
        self.assertEqual(x.a, 1)

        app.request("/bar")
        self.assertEqual(x.a, 2)

    def test_changequery(self):
        urls = ("/", "index")

        class index:
            def GET(self):
                return web.changequery(x=1)

        app = web.application(urls, locals())

        def f(path):
            return app.request(path).data

        self.assertEqual(f("/?x=2"), b"/?x=1")

        p = f("/?y=1&y=2&x=2")
        self.assertTrue(p == b"/?y=1&y=2&x=1" or p == b"/?x=1&y=1&y=2")

    def test_setcookie(self):
        urls = ("/", "index")

        class index:
            def GET(self):
                web.setcookie("foo", "bar")
                return "hello"

        app = web.application(urls, locals())

        def f(script_name=""):
            response = app.request("/", env={"SCRIPT_NAME": script_name})
            return response.headers["Set-Cookie"]

        self.assertEqual(f(""), "foo=bar; Path=/")
        self.assertEqual(f("/admin"), "foo=bar; Path=/admin/")

    def test_stopsimpleserver(self):
        urls = ("/", "index")

        class index:
            def GET(self):
                pass

        # reset command-line arguments
        sys.argv = ["code.py"]

        app = web.application(urls, locals())
        thread = threading.Thread(target=app.run)

        thread.start()
        time.sleep(1)
        self.assertTrue(thread.is_alive())

        app.stop()
        thread.join(timeout=1)
        self.assertFalse(thread.is_alive())