Debian Codegraph @

test/units/module_utils/urls/test_gzip.py

raw
1 # -*- coding: utf-8 -*-
2 # (c) 2021 Matt Martz <[email protected]>
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 import gzip
8 import io
9 import sys
10 import http.client
11
12 from ansible.module_utils.urls import GzipDecodedReader, Request
13
14 import pytest
15
16
17 def compress(data):
18 buf = io.BytesIO()
19 try:
20 f = gzip.GzipFile(fileobj=buf, mode='wb')
21 f.write(data)
22 finally:
23 f.close()
24 return buf.getvalue()
25
26
27 class Sock(io.BytesIO):
28 def makefile(self, *args, **kwds):
29 return self
30
31
32 @pytest.fixture
33 def urlopen_mock(mocker):
34 return mocker.patch('ansible.module_utils.urls.urllib.request.urlopen')
35
36
37 JSON_DATA = b'{"foo": "bar", "baz": "qux", "sandwich": "ham", "tech_level": "pickle", "pop": "corn", "ansible": "awesome"}'
38
39
40 RESP = b"""HTTP/1.1 200 OK
41 Content-Type: application/json; charset=utf-8
42 Set-Cookie: foo
43 Set-Cookie: bar
44 Content-Length: 108
45
46 %s""" % JSON_DATA
47
48 GZIP_RESP = b"""HTTP/1.1 200 OK
49 Content-Type: application/json; charset=utf-8
50 Set-Cookie: foo
51 Set-Cookie: bar
52 Content-Encoding: gzip
53 Content-Length: 100
54
55 %s""" % compress(JSON_DATA)
56
57
58 def test_Request_open_gzip(urlopen_mock):
59 h = http.client.HTTPResponse(
60 Sock(GZIP_RESP),
61 method='GET',
62 )
63 h.begin()
64
65 urlopen_mock.return_value = h
66
67 r = Request().open('GET', 'https://ansible.com/')
68 assert isinstance(r.fp, GzipDecodedReader)
69 assert r.read() == JSON_DATA
70
71
72 def test_Request_open_not_gzip(urlopen_mock):
73 h = http.client.HTTPResponse(
74 Sock(RESP),
75 method='GET',
76 )
77 h.begin()
78
79 urlopen_mock.return_value = h
80
81 r = Request().open('GET', 'https://ansible.com/')
82 assert not isinstance(r.fp, GzipDecodedReader)
83 assert r.read() == JSON_DATA
84
85
86 def test_Request_open_decompress_false(urlopen_mock):
87 h = http.client.HTTPResponse(
88 Sock(RESP),
89 method='GET',
90 )
91 h.begin()
92
93 urlopen_mock.return_value = h
94
95 r = Request().open('GET', 'https://ansible.com/', decompress=False)
96 assert not isinstance(r.fp, GzipDecodedReader)
97 assert r.read() == JSON_DATA
98
99
100 def test_GzipDecodedReader_no_gzip(monkeypatch, mocker):
101 monkeypatch.delitem(sys.modules, 'gzip')
102 monkeypatch.delitem(sys.modules, 'ansible.module_utils.urls')
103
104 orig_import = __import__
105
106 def _import(*args):
107 if args[0] == 'gzip':
108 raise ImportError
109 return orig_import(*args)
110
111 mocker.patch('builtins.__import__', _import)
112
113 mod = __import__('ansible.module_utils.urls').module_utils.urls
114 assert mod.HAS_GZIP is False
115 pytest.raises(mod.MissingModuleError, mod.GzipDecodedReader, None)