Skip to content

Commit 47391d4

Browse files
committed
Fix deprecation and resource warnings.
Signed-off-by: Ivan Kanakarakis <[email protected]>
1 parent 408596b commit 47391d4

File tree

10 files changed

+43
-63
lines changed

10 files changed

+43
-63
lines changed

src/saml2/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -586,7 +586,8 @@ def get_ns_map(self, elements, uri_set):
586586

587587
for elem in elements:
588588
uri_set = self.get_ns_map_attribute(elem.attrib, uri_set)
589-
uri_set = self.get_ns_map(elem.getchildren(), uri_set)
589+
children = list(elem)
590+
uri_set = self.get_ns_map(children, uri_set)
590591
uri = self.tag_get_uri(elem)
591592
if uri is not None:
592593
uri_set.add(uri)
@@ -651,7 +652,7 @@ def set_prefixes(self, elem, prefix_map):
651652

652653
# fixup all elements in the tree
653654
memo = {}
654-
for elem in elem.getiterator():
655+
for elem in elem.iter():
655656
self.fixup_element_prefixes(elem, uri_map, memo)
656657

657658
def fixup_element_prefixes(self, elem, uri_map, memo):

src/saml2/cert.py

Lines changed: 5 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,6 @@ def create_certificate(self, cert_info, request=False, valid_from=0,
150150
cert.set_pubkey(k)
151151
cert.sign(k, hash_alg)
152152

153-
filesCreated = False
154153
try:
155154
if request:
156155
tmp_cert = crypto.dump_certificate_request(crypto.FILETYPE_PEM,
@@ -169,33 +168,18 @@ def create_certificate(self, cert_info, request=False, valid_from=0,
169168
else:
170169
tmp_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k)
171170
if write_to_file:
172-
fc = open(c_f, "wt")
173-
fk = open(k_f, "wt")
174-
175-
if request:
176-
fc.write(tmp_cert.decode('utf-8'))
177-
else:
171+
with open(c_f, 'wt') as fc:
178172
fc.write(tmp_cert.decode('utf-8'))
179-
fk.write(tmp_key.decode('utf-8'))
180-
filesCreated = True
181-
try:
182-
fc.close()
183-
except:
184-
pass
185-
186-
try:
187-
fk.close()
188-
except:
189-
pass
173+
with open(k_f, 'wt') as fk:
174+
fk.write(tmp_key.decode('utf-8'))
190175
return c_f, k_f
191176
return tmp_cert, tmp_key
192177
except Exception as ex:
193178
raise CertificateError("Certificate cannot be generated.", ex)
194179

195180
def write_str_to_file(self, file, str_data):
196-
f = open(file, "wt")
197-
f.write(str_data)
198-
f.close()
181+
with open(file, 'wt') as f:
182+
f.write(str_data)
199183

200184
def read_str_from_file(self, file, type="pem"):
201185
with open(file, 'rb') as f:

src/saml2/config.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,6 @@ def load_file(self, config_file, metadata_construction=False):
373373
config_file = config_file[:-3]
374374

375375
mod = self._load(config_file)
376-
# return self.load(eval(open(config_file).read()))
377376
return self.load(copy.deepcopy(mod.CONFIG), metadata_construction)
378377

379378
def load_metadata(self, metadata_conf):

src/saml2/eptid.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ def get(self, idp, sp, *args):
5656
self[key] = val
5757
return val
5858

59+
def close(self):
60+
pass
61+
5962

6063
class EptidShelve(Eptid):
6164
def __init__(self, secret, filename):
@@ -64,3 +67,6 @@ def __init__(self, secret, filename):
6467
if filename.endswith('.db'):
6568
filename = filename.rsplit('.db', 1)[0]
6669
self._db = shelve.open(filename, writeback=True, protocol=2)
70+
71+
def close(self):
72+
self._db.close()

src/saml2/mdbcache.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def __init__(self, server=None, debug=0, db=None):
3131
self.debug = debug
3232

3333
def delete(self, subject_id):
34-
self._cache.remove({"subject_id": subject_id})
34+
self._cache.delete_many({'subject_id': subject_id})
3535

3636
def get_identity(self, subject_id, entities=None,
3737
check_not_on_or_after=True):
@@ -196,4 +196,4 @@ def valid_to(self, subject_id, entity_id, newtime):
196196
{"$set": {"timestamp": newtime}})
197197

198198
def clear(self):
199-
self._cache.remove()
199+
self._cache.delete_many({})

src/saml2/mongo_store.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,11 +178,7 @@ def handle_name_id_mapping_request(self, name_id, name_id_policy):
178178
# else create and return a new one
179179
return self.construct_nameid(_id, name_id_policy=name_id_policy)
180180

181-
def close(self):
182-
pass
183-
184181

185-
#------------------------------------------------------------------------------
186182
class MDB(object):
187183
primary_key = "mdb"
188184

src/saml2/s2repoze/plugins/formswithhidden.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,8 @@ def make_plugin(login_form_qs='__do_login', rememberer_name=None, form=None):
116116
raise ValueError(
117117
'must include rememberer key (name of another IIdentifier plugin)')
118118
if form is not None:
119-
form = open(form).read()
119+
with open(form, 'r') as f:
120+
form = f.read()
120121
plugin = FormHiddenPlugin(login_form_qs, rememberer_name, form)
121122
return plugin
122123

src/saml2/saml.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
#
44
# Generated Mon May 2 14:23:33 2011 by parse_xsd.py version 0.4.
55
#
6+
import base64
7+
68
from saml2.validate import valid_ipv4, MustValueError
79
from saml2.validate import valid_ipv6
810
from saml2.validate import ShouldValueError
@@ -81,11 +83,12 @@
8183
SCM_SENDER_VOUCHES = "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches"
8284
SCM_BEARER = "urn:oasis:names:tc:SAML:2.0:cm:bearer"
8385

84-
# -----------------------------------------------------------------------------
8586
XSD = "xs:"
8687
NS_SOAP_ENC = "http://schemas.xmlsoap.org/soap/encoding/"
8788

88-
# -----------------------------------------------------------------------------
89+
90+
_b64_decode_fn = getattr(base64, 'decodebytes', base64.decodestring)
91+
_b64_encode_fn = getattr(base64, 'encodebytes', base64.encodestring)
8992

9093

9194
def _decode_attribute_value(typ, text):
@@ -96,11 +99,9 @@ def _decode_attribute_value(typ, text):
9699
if typ == XSD + "float" or typ == XSD + "double":
97100
return str(float(text))
98101
if typ == XSD + "boolean":
99-
return "%s" % (text == "true" or text == "True")
102+
return str(text.lower() == "true")
100103
if typ == XSD + "base64Binary":
101-
import base64
102-
103-
return base64.decodestring(text)
104+
return _b64_decode_fn(text)
104105
raise ValueError("type %s not supported" % type)
105106

106107

@@ -124,9 +125,7 @@ def _verify_value_type(typ, val):
124125
else:
125126
raise ValueError("Faulty boolean value")
126127
if typ == XSD + "base64Binary":
127-
import base64
128-
129-
return base64.decodestring(val.encode('utf-8'))
128+
return _b64_decode_fn(val.encode())
130129

131130

132131
class AttributeValueBase(SamlBase):
@@ -181,7 +180,6 @@ def set_type(self, typ):
181180
except AttributeError:
182181
self._extatt['xmlns:xs'] = XS_NAMESPACE
183182

184-
185183
def get_type(self):
186184
try:
187185
return self.extension_attributes[XSI_TYPE]
@@ -204,13 +202,11 @@ def clear_type(self):
204202
def set_text(self, val, base64encode=False):
205203
typ = self.get_type()
206204
if base64encode:
207-
import base64
208-
209-
val = base64.encodestring(val)
205+
val = _b64_encode_fn(val)
210206
self.set_type("xs:base64Binary")
211207
else:
212208
if isinstance(val, six.binary_type):
213-
val = val.decode('utf-8')
209+
val = val.decode()
214210
if isinstance(val, six.string_types):
215211
if not typ:
216212
self.set_type("xs:string")

src/saml2/server.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,6 @@ def choose_session_storage(self):
113113
typ, data = _spec
114114
if typ.lower() == "mongodb":
115115
from saml2.mongo_store import SessionStorageMDB
116-
117116
return SessionStorageMDB(database=data, collection="session")
118117

119118
raise NotImplementedError("No such storage type implemented")
@@ -142,15 +141,12 @@ def init_config(self, stype="idp"):
142141
idb = _shelve_compat(addr, writeback=True, protocol=2)
143142
elif typ == "memcached":
144143
import memcache
145-
146144
idb = memcache.Client(addr)
147145
elif typ == "dict": # in-memory dictionary
148146
idb = {}
149147
elif typ == "mongodb":
150148
from saml2.mongo_store import IdentMDB
151-
152149
self.ident = IdentMDB(database=addr, collection="ident")
153-
154150
elif typ == "identdb":
155151
mod, clas = addr.rsplit('.', 1)
156152
mod = importlib.import_module(mod)
@@ -182,7 +178,6 @@ def init_config(self, stype="idp"):
182178
self.eptid = EptidShelve(secret, addr)
183179
elif typ == "mongodb":
184180
from saml2.mongo_store import EptidMDB
185-
186181
self.eptid = EptidMDB(secret, database=addr,
187182
collection="eptid")
188183
else:

tests/test_51_client.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@
5353
"authn_auth": "http://www.example.com/login"
5454
}
5555

56+
encode_fn = getattr(base64, 'encodebytes', base64.encodestring)
57+
5658

5759
def generate_cert():
5860
sn = uuid.uuid4().urn
@@ -177,7 +179,7 @@ def test_create_attribute_query1(self):
177179
"E8042FB4-4D5B-48C3-8E14-8EDD852790DD",
178180
format=saml.NAMEID_FORMAT_PERSISTENT,
179181
message_id="id1")
180-
reqstr = "%s" % req.to_string().decode('utf-8')
182+
reqstr = "%s" % req.to_string().decode()
181183

182184
assert req.destination == "https://idp.example.com/idp/"
183185
assert req.id == "id1"
@@ -411,7 +413,7 @@ def test_response_1(self):
411413

412414
resp_str = "%s" % resp
413415

414-
resp_str = base64.encodestring(resp_str.encode('utf-8'))
416+
resp_str = encode_fn(resp_str.encode())
415417

416418
authn_response = self.client.parse_authn_request_response(
417419
resp_str, BINDING_HTTP_POST,
@@ -455,7 +457,7 @@ def test_response_1(self):
455457
456458
authn=AUTHN)
457459

458-
resp_str = base64.encodestring(resp_str.encode('utf-8'))
460+
resp_str = encode_fn(resp_str.encode())
459461

460462
self.client.parse_authn_request_response(
461463
resp_str, BINDING_HTTP_POST,
@@ -505,7 +507,7 @@ def test_response_2(self):
505507

506508
resp_str = "%s" % resp
507509

508-
resp_str = base64.encodestring(resp_str.encode('utf-8'))
510+
resp_str = encode_fn(resp_str.encode())
509511

510512
authn_response = _client.parse_authn_request_response(
511513
resp_str, BINDING_HTTP_POST,
@@ -540,7 +542,7 @@ def test_response_3(self):
540542

541543
resp_str = "%s" % resp
542544

543-
resp_str = base64.encodestring(resp_str.encode('utf-8'))
545+
resp_str = encode_fn(resp_str.encode())
544546

545547
authn_response = _client.parse_authn_request_response(
546548
resp_str, BINDING_HTTP_POST,
@@ -575,7 +577,7 @@ def test_response_4(self):
575577

576578
resp_str = "%s" % resp
577579

578-
resp_str = base64.encodestring(resp_str.encode('utf-8'))
580+
resp_str = encode_fn(resp_str.encode())
579581

580582
authn_response = _client.parse_authn_request_response(
581583
resp_str, BINDING_HTTP_POST,
@@ -619,7 +621,7 @@ def test_response_5(self):
619621

620622
resp_str = "%s" % resp
621623

622-
resp_str = base64.encodestring(resp_str.encode('utf-8'))
624+
resp_str = encode_fn(resp_str.encode())
623625

624626
authn_response = _client.parse_authn_request_response(
625627
resp_str, BINDING_HTTP_POST,
@@ -672,7 +674,7 @@ def test_response_6(self):
672674

673675
resp_str = "%s" % resp
674676

675-
resp_str = base64.encodestring(resp_str.encode('utf-8'))
677+
resp_str = encode_fn(resp_str.encode())
676678

677679
authn_response = _client.parse_authn_request_response(
678680
resp_str, BINDING_HTTP_POST,
@@ -708,7 +710,7 @@ def test_response_7(self):
708710

709711
resp_str = "%s" % resp
710712

711-
resp_str = base64.encodestring(resp_str.encode('utf-8'))
713+
resp_str = encode_fn(resp_str.encode())
712714

713715
authn_response = _client.parse_authn_request_response(
714716
resp_str, BINDING_HTTP_POST,
@@ -751,7 +753,7 @@ def test_response_8(self):
751753

752754
resp_str = "%s" % resp
753755

754-
resp_str = base64.encodestring(resp_str.encode('utf-8'))
756+
resp_str = encode_fn(resp_str.encode())
755757

756758
authn_response = _client.parse_authn_request_response(
757759
resp_str, BINDING_HTTP_POST,
@@ -927,7 +929,7 @@ def test_sign_then_encrypt_assertion2(self):
927929

928930
# seresp = samlp.response_from_string(enctext)
929931

930-
resp_str = base64.encodestring(enctext.encode('utf-8'))
932+
resp_str = encode_fn(enctext.encode())
931933
# Now over to the client side
932934
# Explicitely allow unsigned responses for this and the following 2 tests
933935
self.client.want_response_signed = False
@@ -1030,7 +1032,7 @@ def test_sign_then_encrypt_assertion_advice_1(self):
10301032

10311033
# seresp = samlp.response_from_string(enctext)
10321034

1033-
resp_str = base64.encodestring(enctext.encode('utf-8'))
1035+
resp_str = encode_fn(enctext.encode())
10341036
# Now over to the client side
10351037
resp = self.client.parse_authn_request_response(
10361038
resp_str, BINDING_HTTP_POST,
@@ -1315,7 +1317,7 @@ def test_sign_then_encrypt_assertion_advice_2(self):
13151317

13161318
# seresp = samlp.response_from_string(enctext)
13171319

1318-
resp_str = base64.encodestring(str(response).encode('utf-8'))
1320+
resp_str = encode_fn(str(response).encode())
13191321
# Now over to the client side
13201322
resp = self.client.parse_authn_request_response(
13211323
resp_str, BINDING_HTTP_POST,

0 commit comments

Comments
 (0)