summaryrefslogtreecommitdiffstats
path: root/testing/mozbase/mozfile/tests/test_load.py
blob: 13a5b519c133014a1d7903a48ec431fcf560ca08 (plain)
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
#!/usr/bin/env python

"""
tests for mozfile.load
"""

import mozhttpd
import os
import tempfile
import unittest
from mozfile import load


class TestLoad(unittest.TestCase):
    """test the load function"""

    def test_http(self):
        """test with mozhttpd and a http:// URL"""

        def example(request):
            """example request handler"""
            body = 'example'
            return (200, {'Content-type': 'text/plain',
                          'Content-length': len(body)
                          }, body)

        host = '127.0.0.1'
        httpd = mozhttpd.MozHttpd(host=host,
                                  urlhandlers=[{'method': 'GET',
                                                'path': '.*',
                                                'function': example}])
        try:
            httpd.start(block=False)
            content = load(httpd.get_url()).read()
            self.assertEqual(content, 'example')
        finally:
            httpd.stop()

    def test_file_path(self):
        """test loading from file path"""
        try:
            # create a temporary file
            tmp = tempfile.NamedTemporaryFile(delete=False)
            tmp.write('foo bar')
            tmp.close()

            # read the file
            contents = file(tmp.name).read()
            self.assertEqual(contents, 'foo bar')

            # read the file with load and a file path
            self.assertEqual(load(tmp.name).read(), contents)

            # read the file with load and a file URL
            self.assertEqual(load('file://%s' % tmp.name).read(), contents)
        finally:
            # remove the tempfile
            if os.path.exists(tmp.name):
                os.remove(tmp.name)

if __name__ == '__main__':
    unittest.main()