Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

680 lines · 21.7 KiB · Python

Last changed by

Merge pull request #4134 from mlcrazy/masterCory Benfieldbefore adoption132040c

History of this file

Take it

The walk stopped after 200 commits: lines older than 8344b0b point at it.

link to twitterKenneth Reitzbefore adoption8344b0b

lines 1–2why, one step back
1# -*- coding: utf-8 -*-
2

Merge pull request #3979 from schlamar/bypass-proxyCory Benfieldbefore adoption216aee4

line 3why, one step back
3import os

Merge pull request #4134 from mlcrazy/masterCory Benfieldbefore adoption132040c

line 4why, one step back
4import copy

link to twitterKenneth Reitzbefore adoption8344b0b

lines 5–20why, one step back
5from io import BytesIO
67import pytest8from requests import compat9from requests.cookies import RequestsCookieJar10from requests.structures import CaseInsensitiveDict11from requests.utils import (12 address_in_network, dotted_netmask,13 get_auth_from_url, get_encoding_from_headers,14 get_encodings_from_content, get_environ_proxies,15 guess_filename, guess_json_utf, is_ipv4_address,16 is_valid_cidr, iter_slices, parse_dict_header,17 parse_header_links, prepend_scheme_if_needed,18 requote_uri, select_proxy, should_bypass_proxies, super_len,19 to_key_val_list, to_native_string,20 unquote_header_value, unquote_unreserved,

Merge pull request #4134 from mlcrazy/masterCory Benfieldbefore adoption132040c

line 21why, one step back
21 urldefragauth, add_dict_to_cookiejar, set_environ)

link to twitterKenneth Reitzbefore adoption8344b0b

lines 22–165why, one step back
22from requests._internal_utils import unicode_is_ascii
2324from .compat import StringIO, cStringIO252627class TestSuperLen:2829 @pytest.mark.parametrize(30 'stream, value', (31 (StringIO.StringIO, 'Test'),32 (BytesIO, b'Test'),33 pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),34 ))35 def test_io_streams(self, stream, value):36 """Ensures that we properly deal with different kinds of IO streams."""37 assert super_len(stream()) == 038 assert super_len(stream(value)) == 43940 def test_super_len_correctly_calculates_len_of_partially_read_file(self):41 """Ensure that we handle partially consumed file like objects."""42 s = StringIO.StringIO()43 s.write('foobarbogus')44 assert super_len(s) == 04546 @pytest.mark.parametrize('error', [IOError, OSError])47 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):48 """If tell() raises errors, assume the cursor is at position zero."""49 class BoomFile(object):50 def __len__(self):51 return 55253 def tell(self):54 raise error()5556 assert super_len(BoomFile()) == 05758 @pytest.mark.parametrize('error', [IOError, OSError])59 def test_super_len_tell_ioerror(self, error):60 """Ensure that if tell gives an IOError super_len doesn't fail"""61 class NoLenBoomFile(object):62 def tell(self):63 raise error()6465 def seek(self, offset, whence):66 pass6768 assert super_len(NoLenBoomFile()) == 06970 def test_string(self):71 assert super_len('Test') == 47273 @pytest.mark.parametrize(74 'mode, warnings_num', (75 ('r', 1),76 ('rb', 0),77 ))78 def test_file(self, tmpdir, mode, warnings_num, recwarn):79 file_obj = tmpdir.join('test.txt')80 file_obj.write('Test')81 with file_obj.open(mode) as fd:82 assert super_len(fd) == 483 assert len(recwarn) == warnings_num8485 def test_super_len_with__len__(self):86 foo = [1,2,3,4]87 len_foo = super_len(foo)88 assert len_foo == 48990 def test_super_len_with_no__len__(self):91 class LenFile(object):92 def __init__(self):93 self.len = 59495 assert super_len(LenFile()) == 59697 def test_super_len_with_tell(self):98 foo = StringIO.StringIO('12345')99 assert super_len(foo) == 5100 foo.read(2)101 assert super_len(foo) == 3102103 def test_super_len_with_fileno(self):104 with open(__file__, 'rb') as f:105 length = super_len(f)106 file_data = f.read()107 assert length == len(file_data)108109 def test_super_len_with_no_matches(self):110 """Ensure that objects without any length methods default to 0"""111 assert super_len(object()) == 0112113114class TestToKeyValList:115116 @pytest.mark.parametrize(117 'value, expected', (118 ([('key', 'val')], [('key', 'val')]),119 ((('key', 'val'), ), [('key', 'val')]),120 ({'key': 'val'}, [('key', 'val')]),121 (None, None)122 ))123 def test_valid(self, value, expected):124 assert to_key_val_list(value) == expected125126 def test_invalid(self):127 with pytest.raises(ValueError):128 to_key_val_list('string')129130131class TestUnquoteHeaderValue:132133 @pytest.mark.parametrize(134 'value, expected', (135 (None, None),136 ('Test', 'Test'),137 ('"Test"', 'Test'),138 ('"Test\\\\"', 'Test\\'),139 ('"\\\\Comp\\Res"', '\\Comp\\Res'),140 ))141 def test_valid(self, value, expected):142 assert unquote_header_value(value) == expected143144 def test_is_filename(self):145 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'146147148class TestGetEnvironProxies:149 """Ensures that IP addresses are correctly matches with ranges150 in no_proxy variable.151 """152153 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])154 def no_proxy(self, request, monkeypatch):155 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')156157 @pytest.mark.parametrize(158 'url', (159 'http://192.168.0.1:5000/',160 'http://192.168.0.1/',161 'http://172.16.1.1/',162 'http://172.16.1.1:5000/',163 'http://localhost.localdomain:5000/v1.0/',164 ))165 def test_bypass(self, url):

Merge pull request #3865 from JohnVillalovos/masterKenneth Reitzbefore adoption6bd6249

line 166why, one step back
166 assert get_environ_proxies(url, no_proxy=None) == {}

link to twitterKenneth Reitzbefore adoption8344b0b

lines 167–174why, one step back
167
168 @pytest.mark.parametrize(169 'url', (170 'http://192.168.1.1:5000/',171 'http://192.168.1.1/',172 'http://www.requests.com/',173 ))174 def test_not_bypass(self, url):

Merge pull request #3865 from JohnVillalovos/masterKenneth Reitzbefore adoption6bd6249

line 175why, one step back
175 assert get_environ_proxies(url, no_proxy=None) != {}

link to twitterKenneth Reitzbefore adoption8344b0b

line 176why, one step back
176

Merge pull request #3865 from JohnVillalovos/masterKenneth Reitzbefore adoption6bd6249

lines 177–185why, one step back
177 @pytest.mark.parametrize(
178 'url', (179 'http://192.168.1.1:5000/',180 'http://192.168.1.1/',181 'http://www.requests.com/',182 ))183 def test_bypass_no_proxy_keyword(self, url):184 no_proxy = '192.168.1.1,requests.com'185 assert get_environ_proxies(url, no_proxy=no_proxy) == {}

link to twitterKenneth Reitzbefore adoption8344b0b

line 186why, one step back
186

Merge pull request #3865 from JohnVillalovos/masterKenneth Reitzbefore adoption6bd6249

lines 187–202why, one step back
187 @pytest.mark.parametrize(
188 'url', (189 'http://192.168.0.1:5000/',190 'http://192.168.0.1/',191 'http://172.16.1.1/',192 'http://172.16.1.1:5000/',193 'http://localhost.localdomain:5000/v1.0/',194 ))195 def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):196 # This is testing that the 'no_proxy' argument overrides the197 # environment variable 'no_proxy'198 monkeypatch.setenv('http_proxy', 'http://proxy.example.com:3128/')199 no_proxy = '192.168.1.1,requests.com'200 assert get_environ_proxies(url, no_proxy=no_proxy) != {}201202

link to twitterKenneth Reitzbefore adoption8344b0b

lines 203–370why, one step back
203class TestIsIPv4Address:
204205 def test_valid(self):206 assert is_ipv4_address('8.8.8.8')207208 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))209 def test_invalid(self, value):210 assert not is_ipv4_address(value)211212213class TestIsValidCIDR:214215 def test_valid(self):216 assert is_valid_cidr('192.168.1.0/24')217218 @pytest.mark.parametrize(219 'value', (220 '8.8.8.8',221 '192.168.1.0/a',222 '192.168.1.0/128',223 '192.168.1.0/-1',224 '192.168.1.999/24',225 ))226 def test_invalid(self, value):227 assert not is_valid_cidr(value)228229230class TestAddressInNetwork:231232 def test_valid(self):233 assert address_in_network('192.168.1.1', '192.168.1.0/24')234235 def test_invalid(self):236 assert not address_in_network('172.16.0.1', '192.168.1.0/24')237238239class TestGuessFilename:240241 @pytest.mark.parametrize(242 'value', (1, type('Fake', (object,), {'name': 1})()),243 )244 def test_guess_filename_invalid(self, value):245 assert guess_filename(value) is None246247 @pytest.mark.parametrize(248 'value, expected_type', (249 (b'value', compat.bytes),250 (b'value'.decode('utf-8'), compat.str)251 ))252 def test_guess_filename_valid(self, value, expected_type):253 obj = type('Fake', (object,), {'name': value})()254 result = guess_filename(obj)255 assert result == value256 assert isinstance(result, expected_type)257258259class TestContentEncodingDetection:260261 def test_none(self):262 encodings = get_encodings_from_content('')263 assert not len(encodings)264265 @pytest.mark.parametrize(266 'content', (267 # HTML5 meta charset attribute268 '<meta charset="UTF-8">',269 # HTML4 pragma directive270 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',271 # XHTML 1.x served with text/html MIME type272 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',273 # XHTML 1.x served as XML274 '<?xml version="1.0" encoding="UTF-8"?>',275 ))276 def test_pragmas(self, content):277 encodings = get_encodings_from_content(content)278 assert len(encodings) == 1279 assert encodings[0] == 'UTF-8'280281 def test_precedence(self):282 content = '''283 <?xml version="1.0" encoding="XML"?>284 <meta charset="HTML5">285 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />286 '''.strip()287 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']288289290class TestGuessJSONUTF:291292 @pytest.mark.parametrize(293 'encoding', (294 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',295 'utf-32-be', 'utf-32-le'296 ))297 def test_encoded(self, encoding):298 data = '{}'.encode(encoding)299 assert guess_json_utf(data) == encoding300301 def test_bad_utf_like_encoding(self):302 assert guess_json_utf(b'\x00\x00\x00\x00') is None303304 @pytest.mark.parametrize(305 ('encoding', 'expected'), (306 ('utf-16-be', 'utf-16'),307 ('utf-16-le', 'utf-16'),308 ('utf-32-be', 'utf-32'),309 ('utf-32-le', 'utf-32')310 ))311 def test_guess_by_bom(self, encoding, expected):312 data = u'\ufeff{}'.encode(encoding)313 assert guess_json_utf(data) == expected314315316USER = PASSWORD = "%!*'();:@&=+$,/?#[] "317ENCODED_USER = compat.quote(USER, '')318ENCODED_PASSWORD = compat.quote(PASSWORD, '')319320321@pytest.mark.parametrize(322 'url, auth', (323 (324 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +325 'request.com/url.html#test',326 (USER, PASSWORD)327 ),328 (329 'http://user:pass@complex.url.com/path?query=yes',330 ('user', 'pass')331 ),332 (333 'http://user:pass%20pass@complex.url.com/path?query=yes',334 ('user', 'pass pass')335 ),336 (337 'http://user:pass pass@complex.url.com/path?query=yes',338 ('user', 'pass pass')339 ),340 (341 'http://user%25user:pass@complex.url.com/path?query=yes',342 ('user%user', 'pass')343 ),344 (345 'http://user:pass%23pass@complex.url.com/path?query=yes',346 ('user', 'pass#pass')347 ),348 (349 'http://complex.url.com/path?query=yes',350 ('', '')351 ),352 ))353def test_get_auth_from_url(url, auth):354 assert get_auth_from_url(url) == auth355356357@pytest.mark.parametrize(358 'uri, expected', (359 (360 # Ensure requoting doesn't break expectations361 'http://example.com/fiz?buz=%25ppicture',362 'http://example.com/fiz?buz=%25ppicture',363 ),364 (365 # Ensure we handle unquoted percent signs in redirects366 'http://example.com/fiz?buz=%ppicture',367 'http://example.com/fiz?buz=%25ppicture',368 ),369 ))370def test_requote_uri_with_unquoted_percents(uri, expected):

Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoption916d171

line 371why, one step back
371 """See: https://github.com/requests/requests/issues/2356"""

link to twitterKenneth Reitzbefore adoption8344b0b

lines 372–554why, one step back
372 assert requote_uri(uri) == expected
373374375@pytest.mark.parametrize(376 'uri, expected', (377 (378 # Illegal bytes379 'http://example.com/?a=%--',380 'http://example.com/?a=%--',381 ),382 (383 # Reserved characters384 'http://example.com/?a=%300',385 'http://example.com/?a=00',386 )387 ))388def test_unquote_unreserved(uri, expected):389 assert unquote_unreserved(uri) == expected390391392@pytest.mark.parametrize(393 'mask, expected', (394 (8, '255.0.0.0'),395 (24, '255.255.255.0'),396 (25, '255.255.255.128'),397 ))398def test_dotted_netmask(mask, expected):399 assert dotted_netmask(mask) == expected400401402http_proxies = {'http': 'http://http.proxy',403 'http://some.host': 'http://some.host.proxy'}404all_proxies = {'all': 'socks5://http.proxy',405 'all://some.host': 'socks5://some.host.proxy'}406mixed_proxies = {'http': 'http://http.proxy',407 'http://some.host': 'http://some.host.proxy',408 'all': 'socks5://http.proxy'}409@pytest.mark.parametrize(410 'url, expected, proxies', (411 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),412 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),413 ('hTTp:///path', 'http://http.proxy', http_proxies),414 ('hTTps://Other.Host', None, http_proxies),415 ('file:///etc/motd', None, http_proxies),416417 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),418 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),419 ('hTTp:///path', 'socks5://http.proxy', all_proxies),420 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),421422 ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),423 ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),424 ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),425 ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),426 ('https://', 'socks5://http.proxy', mixed_proxies),427 # XXX: unsure whether this is reasonable behavior428 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),429 ))430def test_select_proxies(url, expected, proxies):431 """Make sure we can select per-host proxies correctly."""432 assert select_proxy(url, proxies) == expected433434435@pytest.mark.parametrize(436 'value, expected', (437 ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),438 ('key_without_value', {'key_without_value': None})439 ))440def test_parse_dict_header(value, expected):441 assert parse_dict_header(value) == expected442443444@pytest.mark.parametrize(445 'value, expected', (446 (447 CaseInsensitiveDict(),448 None449 ),450 (451 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),452 'utf-8'453 ),454 (455 CaseInsensitiveDict({'content-type': 'text/plain'}),456 'ISO-8859-1'457 ),458 ))459def test_get_encoding_from_headers(value, expected):460 assert get_encoding_from_headers(value) == expected461462463@pytest.mark.parametrize(464 'value, length', (465 ('', 0),466 ('T', 1),467 ('Test', 4),468 ('Cont', 0),469 ('Other', -5),470 ('Content', None),471 ))472def test_iter_slices(value, length):473 if length is None or (length <= 0 and len(value) > 0):474 # Reads all content at once475 assert len(list(iter_slices(value, length))) == 1476 else:477 assert len(list(iter_slices(value, 1))) == length478479480@pytest.mark.parametrize(481 'value, expected', (482 (483 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',484 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]485 ),486 (487 '<http:/.../front.jpeg>',488 [{'url': 'http:/.../front.jpeg'}]489 ),490 (491 '<http:/.../front.jpeg>;',492 [{'url': 'http:/.../front.jpeg'}]493 ),494 (495 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',496 [497 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},498 {'url': 'http://.../back.jpeg'}499 ]500 ),501 ))502def test_parse_header_links(value, expected):503 assert parse_header_links(value) == expected504505506@pytest.mark.parametrize(507 'value, expected', (508 ('example.com/path', 'http://example.com/path'),509 ('//example.com/path', 'http://example.com/path'),510 ))511def test_prepend_scheme_if_needed(value, expected):512 assert prepend_scheme_if_needed(value, 'http') == expected513514515@pytest.mark.parametrize(516 'value, expected', (517 ('T', 'T'),518 (b'T', 'T'),519 (u'T', 'T'),520 ))521def test_to_native_string(value, expected):522 assert to_native_string(value) == expected523524525@pytest.mark.parametrize(526 'url, expected', (527 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),528 ('http://example.com/path', 'http://example.com/path'),529 ('//u:p@example.com/path', '//example.com/path'),530 ('//example.com/path', '//example.com/path'),531 ('example.com/path', '//example.com/path'),532 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),533 ))534def test_urldefragauth(url, expected):535 assert urldefragauth(url) == expected536537538@pytest.mark.parametrize(539 'url, expected', (540 ('http://192.168.0.1:5000/', True),541 ('http://192.168.0.1/', True),542 ('http://172.16.1.1/', True),543 ('http://172.16.1.1:5000/', True),544 ('http://localhost.localdomain:5000/v1.0/', True),545 ('http://172.16.1.12/', False),546 ('http://172.16.1.12:5000/', False),547 ('http://google.com:5000/v1.0/', False),548 ))549def test_should_bypass_proxies(url, expected, monkeypatch):550 """Tests for function should_bypass_proxies to check if proxy551 can be bypassed or not552 """553 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')554 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')

Merge pull request #3865 from JohnVillalovos/masterKenneth Reitzbefore adoption6bd6249

line 555why, one step back
555 assert should_bypass_proxies(url, no_proxy=None) == expected

link to twitterKenneth Reitzbefore adoption8344b0b

lines 556–582why, one step back
556
557558@pytest.mark.parametrize(559 'cookiejar', (560 compat.cookielib.CookieJar(),561 RequestsCookieJar()562 ))563def test_add_dict_to_cookiejar(cookiejar):564 """Ensure add_dict_to_cookiejar works for565 non-RequestsCookieJar CookieJars566 """567 cookiedict = {'test': 'cookies',568 'good': 'cookies'}569 cj = add_dict_to_cookiejar(cookiejar, cookiedict)570 cookies = dict((cookie.name, cookie.value) for cookie in cj)571 assert cookiedict == cookies572573574@pytest.mark.parametrize(575 'value, expected', (576 (u'test', True),577 (u'æíöû', False),578 (u'ジェーピーニック', False),579 )580)581def test_unicode_is_ascii(value, expected):582 assert unicode_is_ascii(value) is expected

Merge pull request #3865 from JohnVillalovos/masterKenneth Reitzbefore adoption6bd6249

lines 583–603why, one step back
583
584585@pytest.mark.parametrize(586 'url, expected', (587 ('http://192.168.0.1:5000/', True),588 ('http://192.168.0.1/', True),589 ('http://172.16.1.1/', True),590 ('http://172.16.1.1:5000/', True),591 ('http://localhost.localdomain:5000/v1.0/', True),592 ('http://172.16.1.12/', False),593 ('http://172.16.1.12:5000/', False),594 ('http://google.com:5000/v1.0/', False),595 ))596def test_should_bypass_proxies_no_proxy(597 url, expected, monkeypatch):598 """Tests for function should_bypass_proxies to check if proxy599 can be bypassed or not using the 'no_proxy' argument600 """601 no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'602 # Test 'no_proxy' argument603 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected

Merge pull request #3979 from schlamar/bypass-proxyCory Benfieldbefore adoption216aee4

lines 604–654why, one step back
604
605606@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')607@pytest.mark.parametrize(608 'url, expected, override', (609 ('http://192.168.0.1:5000/', True, None),610 ('http://192.168.0.1/', True, None),611 ('http://172.16.1.1/', True, None),612 ('http://172.16.1.1:5000/', True, None),613 ('http://localhost.localdomain:5000/v1.0/', True, None),614 ('http://172.16.1.22/', False, None),615 ('http://172.16.1.22:5000/', False, None),616 ('http://google.com:5000/v1.0/', False, None),617 ('http://mylocalhostname:5000/v1.0/', True, '<local>'),618 ('http://192.168.0.1/', False, ''),619 ))620def test_should_bypass_proxies_win_registry(url, expected, override,621 monkeypatch):622 """Tests for function should_bypass_proxies to check if proxy623 can be bypassed or not with Windows registry settings624 """625 if override is None:626 override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'627 if compat.is_py3:628 import winreg629 else:630 import _winreg as winreg631632 class RegHandle:633 def Close(self):634 pass635636 ie_settings = RegHandle()637638 def OpenKey(key, subkey):639 return ie_settings640641 def QueryValueEx(key, value_name):642 if key is ie_settings:643 if value_name == 'ProxyEnable':644 return [1]645 elif value_name == 'ProxyOverride':646 return [override]647648 monkeypatch.setenv('http_proxy', '')649 monkeypatch.setenv('https_proxy', '')650 monkeypatch.setenv('ftp_proxy', '')651 monkeypatch.setenv('no_proxy', '')652 monkeypatch.setenv('NO_PROXY', '')653 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)654 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)

Merge pull request #4134 from mlcrazy/masterCory Benfieldbefore adoption132040c

lines 655–680why, one step back
655
656657@pytest.mark.parametrize(658 'env_name, value', (659 ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),660 ('no_proxy', None),661 ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),662 ('a_new_key', None),663 ))664def test_set_environ(env_name, value):665 """Tests set_environ will set environ values and will restore the environ."""666 environ_copy = copy.deepcopy(os.environ)667 with set_environ(env_name, value):668 assert os.environ.get(env_name) == value669670 assert os.environ == environ_copy671672673def test_set_environ_raises_exception():674 """Tests set_environ will raise exceptions in context when the675 value parameter is None."""676 with pytest.raises(Exception) as exception:677 with set_environ('test1', None):678 raise Exception('Expected exception')679680 assert 'Expected exception' in str(exception.value)