testing/mozbase/mozhttpd/tests/paths.py

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:f536bad52217
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # http://creativecommons.org/publicdomain/zero/1.0/
5
6 from mozfile import TemporaryDirectory
7 import mozhttpd
8 import os
9 import unittest
10 import urllib2
11
12 class PathTest(unittest.TestCase):
13 def try_get(self, url, expected_contents):
14 f = urllib2.urlopen(url)
15 self.assertEqual(f.getcode(), 200)
16 self.assertEqual(f.read(), expected_contents)
17
18 def try_get_expect_404(self, url):
19 with self.assertRaises(urllib2.HTTPError) as cm:
20 urllib2.urlopen(url)
21 self.assertEqual(404, cm.exception.code)
22
23 def test_basic(self):
24 """Test that requests to docroot and a path mapping work as expected."""
25 with TemporaryDirectory() as d1, TemporaryDirectory() as d2:
26 open(os.path.join(d1, "test1.txt"), "w").write("test 1 contents")
27 open(os.path.join(d2, "test2.txt"), "w").write("test 2 contents")
28 httpd = mozhttpd.MozHttpd(port=0,
29 docroot=d1,
30 path_mappings={'/files': d2}
31 )
32 httpd.start(block=False)
33 self.try_get(httpd.get_url("/test1.txt"), "test 1 contents")
34 self.try_get(httpd.get_url("/files/test2.txt"), "test 2 contents")
35 self.try_get_expect_404(httpd.get_url("/files/test2_nope.txt"))
36 httpd.stop()
37
38 def test_substring_mappings(self):
39 """Test that a path mapping that's a substring of another works."""
40 with TemporaryDirectory() as d1, TemporaryDirectory() as d2:
41 open(os.path.join(d1, "test1.txt"), "w").write("test 1 contents")
42 open(os.path.join(d2, "test2.txt"), "w").write("test 2 contents")
43 httpd = mozhttpd.MozHttpd(port=0,
44 path_mappings={'/abcxyz': d1,
45 '/abc': d2,}
46 )
47 httpd.start(block=False)
48 self.try_get(httpd.get_url("/abcxyz/test1.txt"), "test 1 contents")
49 self.try_get(httpd.get_url("/abc/test2.txt"), "test 2 contents")
50 httpd.stop()
51
52 def test_multipart_path_mapping(self):
53 """Test that a path mapping with multiple directories works."""
54 with TemporaryDirectory() as d1:
55 open(os.path.join(d1, "test1.txt"), "w").write("test 1 contents")
56 httpd = mozhttpd.MozHttpd(port=0,
57 path_mappings={'/abc/def/ghi': d1}
58 )
59 httpd.start(block=False)
60 self.try_get(httpd.get_url("/abc/def/ghi/test1.txt"), "test 1 contents")
61 self.try_get_expect_404(httpd.get_url("/abc/test1.txt"))
62 self.try_get_expect_404(httpd.get_url("/abc/def/test1.txt"))
63 httpd.stop()
64
65 def test_no_docroot(self):
66 """Test that path mappings with no docroot work."""
67 with TemporaryDirectory() as d1:
68 httpd = mozhttpd.MozHttpd(port=0,
69 path_mappings={'/foo': d1})
70 httpd.start(block=False)
71 self.try_get_expect_404(httpd.get_url())
72 httpd.stop()
73
74 if __name__ == '__main__':
75 unittest.main()

mercurial