From fd5dc7c2dd1f2417373375a35c17bb322fe7972a Mon Sep 17 00:00:00 2001 From: Roland Hedberg Date: Wed, 21 Jul 2010 13:14:26 +0200 Subject: [PATCH] Changed and/or added tests --- tests/test_00_xmldsig.py | 659 ++++++++++++++++++++++ tests/test_01_xmlenc.py | 209 +++++++ tests/test_02_saml.py | 998 +++++++++++++++++++++++++++++++++ tests/test_03_saml2.py | 524 +++++++++++++++++ tests/test_04_samlp.py | 538 ++++++++++++++++++ tests/test_05_md.py | 1143 ++++++++++++++++++++++++++++++++++++++ tests/test_12_s_utils.py | 444 +++++++++++++++ tests/test_43_soap.py | 61 ++ 8 files changed, 4576 insertions(+) create mode 100644 tests/test_00_xmldsig.py create mode 100644 tests/test_01_xmlenc.py create mode 100644 tests/test_02_saml.py create mode 100644 tests/test_03_saml2.py create mode 100644 tests/test_04_samlp.py create mode 100644 tests/test_05_md.py create mode 100644 tests/test_12_s_utils.py create mode 100755 tests/test_43_soap.py diff --git a/tests/test_00_xmldsig.py b/tests/test_00_xmldsig.py new file mode 100644 index 0000000..f57e60a --- /dev/null +++ b/tests/test_00_xmldsig.py @@ -0,0 +1,659 @@ +#!/usr/bin/python +# +# Copyright (C) 2007 SIOS Technology, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for xmldsig""" + +__author__ = 'tmatsuo@example.com (Takashi MATSUO)' + +import unittest +try: + from xml.etree import ElementTree +except ImportError: + from elementtree import ElementTree +import ds_data +import xmldsig as ds + +class TestObject: + + def setup_class(self): + self.object = ds.Object() + + def testAccessors(self): + """Test for Object accessors""" + self.object.id = "object_id" + self.object.mime_type = "test/plain; charset=UTF-8" + self.object.encoding = ds.ENCODING_BASE64 + new_object = ds.object_from_string(self.object.to_string()) + assert new_object.id == "object_id" + assert new_object.mime_type == "test/plain; charset=UTF-8" + assert new_object.encoding == ds.ENCODING_BASE64 + + def testUsingTestData(self): + """Test for object_from_string() using test data""" + new_object = ds.object_from_string(ds_data.TEST_OBJECT) + assert new_object.id == "object_id" + assert new_object.encoding == ds.ENCODING_BASE64 + assert new_object.text.strip() == \ + "V2VkIEp1biAgNCAxMjoxMTowMyBFRFQgMjAwMwo" + + +class TestMgmtData: + + def setup_class(self): + self.mgmt_data = ds.MgmtData() + + def testAccessors(self): + """Test for MgmtData accessors""" + self.mgmt_data.text = "mgmt data" + new_mgmt_data = ds.mgmt_data_from_string(self.mgmt_data.to_string()) + assert new_mgmt_data.text.strip() == "mgmt data" + + def testUsingTestData(self): + """Test for mgmt_data_from_string() using test data""" + new_mgmt_data = ds.mgmt_data_from_string(ds_data.TEST_MGMT_DATA) + assert new_mgmt_data.text.strip() == "mgmt data" + + +class TestSPKISexp: + + def setup_class(self): + self.spki_sexp = ds.SPKISexp() + + def testAccessors(self): + """Test for SPKISexp accessors""" + self.spki_sexp.text = "spki sexp" + new_spki_sexp = ds.spki_sexp_from_string(self.spki_sexp.to_string()) + assert new_spki_sexp.text.strip() == "spki sexp" + + def testUsingTestData(self): + """Test for spki_sexp_from_string() using test data""" + new_spki_sexp = ds.spki_sexp_from_string(ds_data.TEST_SPKI_SEXP) + assert new_spki_sexp.text.strip() == "spki sexp" + + +class TestSPKIData: + + def setup_class(self): + self.spki_data = ds.SPKIData() + + def testAccessors(self): + """Test for SPKIData accessors""" + self.spki_data.spki_sexp.append( + ds.spki_sexp_from_string(ds_data.TEST_SPKI_SEXP)) + new_spki_data = ds.spki_data_from_string(self.spki_data.to_string()) + assert new_spki_data.spki_sexp[0].text.strip() == "spki sexp" + + def testUsingTestData(self): + """Test for spki_data_from_string() using test data""" + new_spki_data = ds.spki_data_from_string(ds_data.TEST_SPKI_DATA) + assert new_spki_data.spki_sexp[0].text.strip() == "spki sexp" + assert new_spki_data.spki_sexp[1].text.strip() == "spki sexp2" + + +class TestPGPData: + + def setup_class(self): + self.pgp_data = ds.PGPData() + + def testAccessors(self): + """Test for PGPData accessors""" + self.pgp_data.pgp_key_id = ds.PGPKeyID(text="pgp key id") + self.pgp_data.pgp_key_packet = ds.PGPKeyPacket(text="pgp key packet") + new_pgp_data = ds.pgp_data_from_string(self.pgp_data.to_string()) + assert isinstance(new_pgp_data.pgp_key_id, ds.PGPKeyID) + assert isinstance(new_pgp_data.pgp_key_packet, ds.PGPKeyPacket) + assert new_pgp_data.pgp_key_id.text.strip() == "pgp key id" + assert new_pgp_data.pgp_key_packet.text.strip() == "pgp key packet" + + def testUsingTestData(self): + """Test for pgp_data_from_string() using test data""" + new_pgp_data = ds.pgp_data_from_string(ds_data.TEST_PGP_DATA) + assert isinstance(new_pgp_data.pgp_key_id, ds.PGPKeyID) + assert isinstance(new_pgp_data.pgp_key_packet, ds.PGPKeyPacket) + assert new_pgp_data.pgp_key_id.text.strip() == "pgp key id" + assert new_pgp_data.pgp_key_packet.text.strip() == "pgp key packet" + + +class TestX509IssuerSerial: + + def setup_class(self): + self.x509_issuer_serial = ds.X509IssuerSerialType() + + def testAccessors(self): + """Test for X509SerialNumber accessors""" + self.x509_issuer_serial.x509_issuer_name = ds.X509IssuerName( + text="issuer name") + self.x509_issuer_serial.x509_serial_number = ds.X509SerialNumber(text="1") + new_x509_issuer_serial = ds.x509_issuer_serial_type_from_string( + self.x509_issuer_serial.to_string()) + assert new_x509_issuer_serial.x509_issuer_name.text.strip() == \ + "issuer name" + assert new_x509_issuer_serial.x509_serial_number.text.strip() == "1" + + def testUsingTestData(self): + """Test for x509_issuer_serial_from_string() using test data""" + new_x509_issuer_serial = ds.x509_issuer_serial_from_string( + ds_data.TEST_X509_ISSUER_SERIAL) + assert new_x509_issuer_serial.x509_issuer_name.text.strip() == \ + "issuer name" + assert new_x509_issuer_serial.x509_serial_number.text.strip() == "1" + + +class TestX509Data: + + def setup_class(self): + self.x509_data = ds.X509Data() + + def testAccessors(self): + """Test for X509Data accessors""" + st = ds.x509_issuer_serial_from_string(ds_data.TEST_X509_ISSUER_SERIAL) + print st + self.x509_data.x509_issuer_serial.append(st) + self.x509_data.x509_ski.append(ds.X509SKI(text="x509 ski")) + self.x509_data.x509_subject_name.append(ds.X509SubjectName( + text="x509 subject name")) + self.x509_data.x509_certificate.append(ds.X509Certificate( + text="x509 certificate")) + self.x509_data.x509_crl.append(ds.X509CRL(text="x509 crl")) + new_x509_data = ds.x509_data_from_string(self.x509_data.to_string()) + print new_x509_data.keyswv() + print new_x509_data.__dict__.keys() + print len(new_x509_data.x509_issuer_serial) + assert isinstance(new_x509_data.x509_issuer_serial[0], + ds.X509IssuerSerialType) + assert new_x509_data.x509_ski[0].text.strip() == "x509 ski" + assert isinstance(new_x509_data.x509_ski[0], ds.X509SKI) + assert new_x509_data.x509_subject_name[0].text.strip() == \ + "x509 subject name" + assert isinstance(new_x509_data.x509_subject_name[0], + ds.X509SubjectName) + assert new_x509_data.x509_certificate[0].text.strip() == \ + "x509 certificate" + assert isinstance(new_x509_data.x509_certificate[0], + ds.X509Certificate) + assert new_x509_data.x509_crl[0].text.strip() == "x509 crl" + assert isinstance(new_x509_data.x509_crl[0],ds.X509CRL) + + def testUsingTestData(self): + """Test for x509_data_from_string() using test data""" + new_x509_data = ds.x509_data_from_string(ds_data.TEST_X509_DATA) + assert isinstance(new_x509_data.x509_issuer_serial[0], + ds.X509IssuerSerial) + assert new_x509_data.x509_ski[0].text.strip() == "x509 ski" + assert isinstance(new_x509_data.x509_ski[0], ds.X509SKI) + assert new_x509_data.x509_subject_name[0].text.strip() == \ + "x509 subject name" + assert isinstance(new_x509_data.x509_subject_name[0], + ds.X509SubjectName) + assert new_x509_data.x509_certificate[0].text.strip() == \ + "x509 certificate" + assert isinstance(new_x509_data.x509_certificate[0], + ds.X509Certificate) + assert new_x509_data.x509_crl[0].text.strip() == "x509 crl" + assert isinstance(new_x509_data.x509_crl[0],ds.X509CRL) + + +class TestTransform: + + def setup_class(self): + self.transform = ds.Transform() + + def testAccessors(self): + """Test for Transform accessors""" + self.transform.x_path.append(ds.XPath(text="xpath")) + self.transform.algorithm = ds.TRANSFORM_ENVELOPED + new_transform = ds.transform_from_string(self.transform.to_string()) + assert isinstance(new_transform.x_path[0], ds.XPath) + assert new_transform.x_path[0].text.strip() == "xpath" + assert new_transform.algorithm == ds.TRANSFORM_ENVELOPED + + def testUsingTestData(self): + """Test for transform_from_string() using test data""" + new_transform = ds.transform_from_string(ds_data.TEST_TRANSFORM) + assert isinstance(new_transform.x_path[0], ds.XPath) + assert new_transform.x_path[0].text.strip() == "xpath" + assert new_transform.algorithm == ds.TRANSFORM_ENVELOPED + + +class TestTransforms: + + def setup_class(self): + self.transforms = ds.Transforms() + + def testAccessors(self): + """Test for Transforms accessors""" + self.transforms.transform.append( + ds.transform_from_string(ds_data.TEST_TRANSFORM)) + self.transforms.transform.append( + ds.transform_from_string(ds_data.TEST_TRANSFORM)) + new_transforms = ds.transforms_from_string(self.transforms.to_string()) + assert isinstance(new_transforms.transform[0], ds.Transform) + assert isinstance(new_transforms.transform[1], ds.Transform) + assert new_transforms.transform[0].algorithm == \ + ds.TRANSFORM_ENVELOPED + assert new_transforms.transform[1].algorithm == \ + ds.TRANSFORM_ENVELOPED + assert new_transforms.transform[0].x_path[0].text.strip() == "xpath" + assert new_transforms.transform[1].x_path[0].text.strip() == "xpath" + + def testUsingTestData(self): + """Test for transform_from_string() using test data""" + new_transforms = ds.transforms_from_string(ds_data.TEST_TRANSFORMS) + assert isinstance(new_transforms.transform[0], ds.Transform) + assert isinstance(new_transforms.transform[1], ds.Transform) + assert new_transforms.transform[0].algorithm == \ + ds.TRANSFORM_ENVELOPED + assert new_transforms.transform[1].algorithm == \ + ds.TRANSFORM_ENVELOPED + assert new_transforms.transform[0].x_path[0].text.strip() == "xpath" + assert new_transforms.transform[1].x_path[0].text.strip() == "xpath" + + +class TestRetrievalMethod: + + def setup_class(self): + self.retrieval_method = ds.RetrievalMethod() + + def testAccessors(self): + """Test for RetrievalMethod accessors""" + self.retrieval_method.uri = "http://www.example.com/URI" + self.retrieval_method.type = "http://www.example.com/Type" + self.retrieval_method.transforms = ds.transforms_from_string( + ds_data.TEST_TRANSFORMS) + new_retrieval_method = ds.retrieval_method_from_string( + self.retrieval_method.to_string()) + assert new_retrieval_method.uri == "http://www.example.com/URI" + assert new_retrieval_method.type == "http://www.example.com/Type" + assert isinstance(new_retrieval_method.transforms, ds.Transforms) + + def testUsingTestData(self): + """Test for retrieval_method_from_string() using test data""" + new_retrieval_method = ds.retrieval_method_from_string( + ds_data.TEST_RETRIEVAL_METHOD) + assert new_retrieval_method.uri == "http://www.example.com/URI" + assert new_retrieval_method.type == "http://www.example.com/Type" + assert isinstance(new_retrieval_method.transforms, ds.Transforms) + + +class TestRSAKeyValue: + + def setup_class(self): + self.rsa_key_value = ds.RSAKeyValue() + + def testAccessors(self): + """Test for RSAKeyValue accessors""" + self.rsa_key_value.modulus = ds.Modulus(text="modulus") + self.rsa_key_value.exponent = ds.Exponent(text="exponent") + new_rsa_key_value = ds.rsa_key_value_from_string(self.rsa_key_value.to_string()) + assert isinstance(new_rsa_key_value.modulus, ds.Modulus) + assert isinstance(new_rsa_key_value.exponent, ds.Exponent) + assert new_rsa_key_value.modulus.text.strip() == "modulus" + assert new_rsa_key_value.exponent.text.strip() == "exponent" + + def testUsingTestData(self): + """Test for rsa_key_value_from_string() using test data""" + new_rsa_key_value = ds.rsa_key_value_from_string( + ds_data.TEST_RSA_KEY_VALUE) + assert isinstance(new_rsa_key_value.modulus, ds.Modulus) + assert isinstance(new_rsa_key_value.exponent, ds.Exponent) + assert new_rsa_key_value.modulus.text.strip() == "modulus" + assert new_rsa_key_value.exponent.text.strip() == "exponent" + + +class TestDSAKeyValue: + + def setup_class(self): + self.dsa_key_value = ds.DSAKeyValue() + + def testAccessors(self): + """Test for DSAKeyValue accessors""" + self.dsa_key_value.p = ds.P(text="p") + self.dsa_key_value.q = ds.Q(text="q") + self.dsa_key_value.g = ds.G(text="g") + self.dsa_key_value.y = ds.Y(text="y") + self.dsa_key_value.j = ds.J(text="j") + self.dsa_key_value.seed = ds.Seed(text="seed") + self.dsa_key_value.pgen_counter = ds.PgenCounter(text="pgen counter") + new_dsa_key_value = ds.dsa_key_value_from_string(self.dsa_key_value.to_string()) + assert isinstance(new_dsa_key_value.p, ds.P) + assert isinstance(new_dsa_key_value.q, ds.Q) + assert isinstance(new_dsa_key_value.g, ds.G) + assert isinstance(new_dsa_key_value.y, ds.Y) + assert isinstance(new_dsa_key_value.j, ds.J) + assert isinstance(new_dsa_key_value.seed, ds.Seed) + assert isinstance(new_dsa_key_value.pgen_counter, ds.PgenCounter) + assert new_dsa_key_value.p.text.strip() == "p" + assert new_dsa_key_value.q.text.strip() == "q" + assert new_dsa_key_value.g.text.strip() == "g" + assert new_dsa_key_value.y.text.strip() == "y" + assert new_dsa_key_value.j.text.strip() == "j" + assert new_dsa_key_value.seed.text.strip() == "seed" + assert new_dsa_key_value.pgen_counter.text.strip() == "pgen counter" + + def testUsingTestData(self): + """Test for dsa_key_value_from_string() using test data""" + new_dsa_key_value = ds.dsa_key_value_from_string( + ds_data.TEST_DSA_KEY_VALUE) + assert isinstance(new_dsa_key_value.p, ds.P) + assert isinstance(new_dsa_key_value.q, ds.Q) + assert isinstance(new_dsa_key_value.g, ds.G) + assert isinstance(new_dsa_key_value.y, ds.Y) + assert isinstance(new_dsa_key_value.j, ds.J) + assert isinstance(new_dsa_key_value.seed, ds.Seed) + assert isinstance(new_dsa_key_value.pgen_counter, ds.PgenCounter) + assert new_dsa_key_value.p.text.strip() == "p" + assert new_dsa_key_value.q.text.strip() == "q" + assert new_dsa_key_value.g.text.strip() == "g" + assert new_dsa_key_value.y.text.strip() == "y" + assert new_dsa_key_value.j.text.strip() == "j" + assert new_dsa_key_value.seed.text.strip() == "seed" + assert new_dsa_key_value.pgen_counter.text.strip() == "pgen counter" + + +class TestKeyValue: + + def setup_class(self): + self.key_value = ds.KeyValue() + + def testAccessors(self): + """Test for KeyValue accessors""" + self.key_value.dsa_key_value = ds.dsa_key_value_from_string( + ds_data.TEST_DSA_KEY_VALUE) + new_key_value = ds.key_value_from_string(self.key_value.to_string()) + assert isinstance(new_key_value.dsa_key_value, ds.DSAKeyValue) + self.key_value.dsa_key_value = None + self.key_value.rsa_key_value = ds.rsa_key_value_from_string( + ds_data.TEST_RSA_KEY_VALUE) + new_key_value = ds.key_value_from_string(self.key_value.to_string()) + assert isinstance(new_key_value.rsa_key_value, ds.RSAKeyValue) + + def testUsingTestData(self): + """Test for key_value_from_string() using test data""" + new_key_value = ds.key_value_from_string(ds_data.TEST_KEY_VALUE1) + assert isinstance(new_key_value.dsa_key_value, ds.DSAKeyValue) + self.key_value.dsa_key_value = None + self.key_value.rsa_key_value = ds.rsa_key_value_from_string( + ds_data.TEST_RSA_KEY_VALUE) + new_key_value = ds.key_value_from_string(ds_data.TEST_KEY_VALUE2) + assert isinstance(new_key_value.rsa_key_value, ds.RSAKeyValue) + + +class TestKeyName: + + def setup_class(self): + self.key_name = ds.KeyName() + + def testAccessors(self): + """Test for KeyName accessors""" + self.key_name.text = "key name" + new_key_name = ds.key_name_from_string(self.key_name.to_string()) + assert new_key_name.text.strip() == "key name" + + def testUsingTestData(self): + """Test for key_name_from_string() using test data""" + new_key_name = ds.key_name_from_string(ds_data.TEST_KEY_NAME) + assert new_key_name.text.strip() == "key name" + + +class TestKeyInfo: + def setup_class(self): + self.key_info = ds.KeyInfo() + + def testAccessors(self): + """Test for KeyInfo accessors""" + self.key_info.key_name.append( + ds.key_name_from_string(ds_data.TEST_KEY_NAME)) + self.key_info.key_value.append( + ds.key_value_from_string(ds_data.TEST_KEY_VALUE1)) + self.key_info.retrieval_method.append( + ds.retrieval_method_from_string(ds_data.TEST_RETRIEVAL_METHOD)) + self.key_info.x509_data.append( + ds.x509_data_from_string(ds_data.TEST_X509_DATA)) + self.key_info.pgp_data.append( + ds.pgp_data_from_string(ds_data.TEST_PGP_DATA)) + self.key_info.spki_data.append( + ds.spki_data_from_string(ds_data.TEST_SPKI_DATA)) + self.key_info.mgmt_data.append( + ds.mgmt_data_from_string(ds_data.TEST_MGMT_DATA)) + self.key_info.id = "id" + new_key_info = ds.key_info_from_string(self.key_info.to_string()) + + assert isinstance(new_key_info.key_name[0], ds.KeyName) + assert isinstance(new_key_info.key_value[0], ds.KeyValue) + assert isinstance(new_key_info.retrieval_method[0], + ds.RetrievalMethod) + assert isinstance(new_key_info.x509_data[0], ds.X509Data) + assert isinstance(new_key_info.pgp_data[0], ds.PGPData) + assert isinstance(new_key_info.spki_data[0], ds.SPKIData) + assert isinstance(new_key_info.mgmt_data[0], ds.MgmtData) + assert new_key_info.id == "id" + + def testUsingTestData(self): + """Test for key_info_from_string() using test data""" + new_key_info = ds.key_info_from_string(ds_data.TEST_KEY_INFO) + assert isinstance(new_key_info.key_name[0], ds.KeyName) + assert isinstance(new_key_info.key_value[0], ds.KeyValue) + assert isinstance(new_key_info.retrieval_method[0], + ds.RetrievalMethod) + assert isinstance(new_key_info.x509_data[0], ds.X509Data) + assert isinstance(new_key_info.pgp_data[0], ds.PGPData) + assert isinstance(new_key_info.spki_data[0], ds.SPKIData) + assert isinstance(new_key_info.mgmt_data[0], ds.MgmtData) + assert new_key_info.id == "id" + + +class TestDigestValue: + + def setup_class(self): + self.digest_value = ds.DigestValue() + + def testAccessors(self): + """Test for DigestValue accessors""" + self.digest_value.text = "digest value" + new_digest_value = ds.digest_value_from_string(self.digest_value.to_string()) + assert new_digest_value.text.strip() == "digest value" + + def testUsingTestData(self): + """Test for digest_value_from_string() using test data""" + new_digest_value = ds.digest_value_from_string(ds_data.TEST_DIGEST_VALUE) + assert new_digest_value.text.strip() == "digest value" + + +class TestDigestMethod: + + def setup_class(self): + self.digest_method = ds.DigestMethod() + + def testAccessors(self): + """Test for DigestMethod accessors""" + self.digest_method.algorithm = ds.DIGEST_SHA1 + new_digest_method = ds.digest_method_from_string( + self.digest_method.to_string()) + assert new_digest_method.algorithm == ds.DIGEST_SHA1 + + def testUsingTestData(self): + """Test for digest_method_from_string() using test data""" + new_digest_method = ds.digest_method_from_string( + ds_data.TEST_DIGEST_METHOD) + assert new_digest_method.algorithm == ds.DIGEST_SHA1 + + +class TestReference: + + def setup_class(self): + self.reference = ds.Reference() + + def testAccessors(self): + """Test for Reference accessors""" + self.reference.transforms = ds.transforms_from_string( + ds_data.TEST_TRANSFORMS) + self.reference.digest_method = ds.digest_method_from_string( + ds_data.TEST_DIGEST_METHOD) + self.reference.digest_value = ds.digest_value_from_string( + ds_data.TEST_DIGEST_VALUE) + self.reference.id = "id" + self.reference.uri = "http://www.example.com/URI" + self.reference.type = "http://www.example.com/Type" + new_reference = ds.reference_from_string(self.reference.to_string()) + assert isinstance(new_reference.transforms, ds.Transforms) + assert isinstance(new_reference.digest_method, ds.DigestMethod) + assert isinstance(new_reference.digest_value, ds.DigestValue) + assert new_reference.id == "id" + assert new_reference.uri == "http://www.example.com/URI" + assert new_reference.type == "http://www.example.com/Type" + + def testUsingTestData(self): + """Test for reference_from_string() using test data""" + new_reference = ds.reference_from_string(ds_data.TEST_REFERENCE) + assert isinstance(new_reference.transforms, ds.Transforms) + assert isinstance(new_reference.digest_method, ds.DigestMethod) + assert isinstance(new_reference.digest_value, ds.DigestValue) + assert new_reference.id == "id" + assert new_reference.uri == "http://www.example.com/URI" + assert new_reference.type == "http://www.example.com/Type" + + +class TestSignatureMethod: + + def setup_class(self): + self.signature_method = ds.SignatureMethod() + + def testAccessors(self): + """Test for SignatureMethod accessors""" + self.signature_method.algorithm = ds.SIG_RSA_SHA1 + self.signature_method.hmac_output_length = ds.HMACOutputLength(text="8") + new_signature_method = ds.signature_method_from_string( + self.signature_method.to_string()) + assert isinstance(new_signature_method.hmac_output_length, + ds.HMACOutputLength) + assert new_signature_method.hmac_output_length.text.strip() == "8" + assert new_signature_method.algorithm == ds.SIG_RSA_SHA1 + + def testUsingTestData(self): + """Test for signature_method_from_string() using test data""" + new_signature_method = ds.signature_method_from_string( + ds_data.TEST_SIGNATURE_METHOD) + assert isinstance(new_signature_method.hmac_output_length, + ds.HMACOutputLength) + assert new_signature_method.hmac_output_length.text.strip() == "8" + assert new_signature_method.algorithm == ds.SIG_RSA_SHA1 + + +class TestCanonicalizationMethod: + + def setup_class(self): + self.canonicalization_method = ds.CanonicalizationMethod() + + def testAccessors(self): + """Test for CanonicalizationMethod accessors""" + self.canonicalization_method.algorithm = ds.C14N_WITH_C + new_canonicalization_method = ds.canonicalization_method_from_string( + self.canonicalization_method.to_string()) + assert new_canonicalization_method.algorithm == ds.C14N_WITH_C + + def testUsingTestData(self): + """Test for canonicalization_method_from_string() using test data""" + new_canonicalization_method = ds.canonicalization_method_from_string( + ds_data.TEST_CANONICALIZATION_METHOD) + assert new_canonicalization_method.algorithm == ds.C14N_WITH_C + + +class TestSignedInfo: + + def setup_class(self): + self.si = ds.SignedInfo() + + def testAccessors(self): + """Test for SignedInfo accessors""" + self.si.id = "id" + self.si.canonicalization_method = ds.canonicalization_method_from_string( + ds_data.TEST_CANONICALIZATION_METHOD) + self.si.signature_method = ds.signature_method_from_string( + ds_data.TEST_SIGNATURE_METHOD) + self.si.reference.append(ds.reference_from_string( + ds_data.TEST_REFERENCE)) + new_si = ds.signed_info_from_string(self.si.to_string()) + assert new_si.id == "id" + assert isinstance(new_si.canonicalization_method, + ds.CanonicalizationMethod) + assert isinstance(new_si.signature_method, ds.SignatureMethod) + assert isinstance(new_si.reference[0], ds.Reference) + + def testUsingTestData(self): + """Test for signed_info_from_string() using test data""" + new_si = ds.signed_info_from_string(ds_data.TEST_SIGNED_INFO) + assert new_si.id == "id" + assert isinstance(new_si.canonicalization_method, + ds.CanonicalizationMethod) + assert isinstance(new_si.signature_method, ds.SignatureMethod) + assert isinstance(new_si.reference[0], ds.Reference) + +class TestSignatureValue: + + def setup_class(self): + self.signature_value = ds.SignatureValue() + + def testAccessors(self): + """Test for SignatureValue accessors""" + self.signature_value.id = "id" + self.signature_value.text = "signature value" + new_signature_value = ds.signature_value_from_string( + self.signature_value.to_string()) + assert new_signature_value.id == "id" + assert new_signature_value.text.strip() == "signature value" + + def testUsingTestData(self): + """Test for signature_value_from_string() using test data""" + new_signature_value = ds.signature_value_from_string( + ds_data.TEST_SIGNATURE_VALUE) + assert new_signature_value.id == "id" + assert new_signature_value.text.strip() == "signature value" + + +class TestSignature: + + def setup_class(self): + self.signature = ds.Signature() + + def testAccessors(self): + """Test for Signature accessors""" + self.signature.id = "id" + self.signature.signed_info = ds.signed_info_from_string( + ds_data.TEST_SIGNED_INFO) + self.signature.signature_value = ds.signature_value_from_string( + ds_data.TEST_SIGNATURE_VALUE) + self.signature.key_info = ds.key_info_from_string(ds_data.TEST_KEY_INFO) + self.signature.object.append(ds.object_from_string(ds_data.TEST_OBJECT)) + + new_signature = ds.signature_from_string(self.signature.to_string()) + assert new_signature.id == "id" + assert isinstance(new_signature.signed_info, ds.SignedInfo) + assert isinstance(new_signature.signature_value, ds.SignatureValue) + assert isinstance(new_signature.key_info, ds.KeyInfo) + assert isinstance(new_signature.object[0], ds.Object) + + def testUsingTestData(self): + """Test for signature_value_from_string() using test data""" + new_signature = ds.signature_from_string(ds_data.TEST_SIGNATURE) + assert new_signature.id == "id" + assert isinstance(new_signature.signed_info, ds.SignedInfo) + assert isinstance(new_signature.signature_value, ds.SignatureValue) + assert isinstance(new_signature.key_info, ds.KeyInfo) + assert isinstance(new_signature.object[0], ds.Object) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_01_xmlenc.py b/tests/test_01_xmlenc.py new file mode 100644 index 0000000..f09710c --- /dev/null +++ b/tests/test_01_xmlenc.py @@ -0,0 +1,209 @@ +import saml2 +import xmlenc as xenc +import xmldsig + +data1 = """ + + + A23B45C56 + +""" + + +def test_1(): + ed = xenc.encrypted_data_from_string(data1) + assert ed + assert ed.mime_type == "text/xml" + assert ed.cipher_data != None + cd = ed.cipher_data + assert cd.cipher_value != None + assert cd.cipher_value.text == "A23B45C56" + +data2 = """ + + + + John Smith + + + DEADBEEF + +""" + +# data2 = """ +# +# +# John Smith +# +# DEADBEEF +# """ + +def test_2(): + ed = xenc.encrypted_data_from_string(data2) + assert ed + print ed + assert ed.type == "http://www.w3.org/2001/04/xmlenc#Element" + assert ed.encryption_method != None + em = ed.encryption_method + assert em.algorithm == 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc' + assert ed.key_info != None + ki = ed.key_info + assert ki.key_name[0].text == "John Smith" + assert ed.cipher_data != None + cd = ed.cipher_data + assert cd.cipher_value != None + assert cd.cipher_value.text == "DEADBEEF" + +data3 = """ + + + + + Sally Doe + + + DEADBEEF + +""" + +def test_3(): + ed = xenc.encrypted_data_from_string(data3) + assert ed + print ed + assert ed.encryption_method != None + em = ed.encryption_method + assert em.algorithm == 'http://www.w3.org/2001/04/xmlenc#aes128-cbc' + assert ed.key_info != None + ki = ed.key_info + assert ki.key_name[0].text == "Sally Doe" + assert len(ki.retrieval_method) == 1 + rm = ki.retrieval_method[0] + assert rm.uri == "#EK" + assert rm.type == "http://www.w3.org/2001/04/xmlenc#EncryptedKey" + assert ed.cipher_data != None + cd = ed.cipher_data + assert cd.cipher_value != None + assert cd.cipher_value.text == "DEADBEEF" + +data4 = """ + + + + John Smith + + + xyzabc + + + + + Sally Doe +""" + + +# data4 = """ +# +# +# John Smith +# +# xyzabc +# +# +# +# Sally Doe +# """ + +def test_4(): + ek = xenc.encrypted_key_from_string(data4) + assert ek + print ek + assert ek.encryption_method != None + em = ek.encryption_method + assert em.algorithm == 'http://www.w3.org/2001/04/xmlenc#rsa-1_5' + assert ek.key_info != None + ki = ek.key_info + assert ki.key_name[0].text == "John Smith" + assert ek.reference_list != None + rl = ek.reference_list + assert len(rl.data_reference) + dr = rl.data_reference[0] + assert dr.uri == "#ED" + assert ek.cipher_data != None + cd = ek.cipher_data + assert cd.cipher_value != None + assert cd.cipher_value.text == "xyzabc" + +data5 = """ + + + + self::text()[parent::rep:CipherValue[@Id="example1"]] + + + + +""" + +def test_5(): + cr = xenc.cipher_reference_from_string(data5) + assert cr + print cr + print cr.keyswv() + trs = cr.transforms + assert len(trs.transform) == 2 + tr = trs.transform[0] + assert tr.algorithm in ["http://www.w3.org/TR/1999/REC-xpath-19991116", + "http://www.w3.org/2000/09/xmldsig#base64"] + if tr.algorithm == "http://www.w3.org/2000/09/xmldsig#base64": + pass + elif tr.algorithm == "http://www.w3.org/TR/1999/REC-xpath-19991116": + assert len(tr.x_path) == 1 + xp = tr.x_path[0] + assert xp.text.strip() == """self::text()[parent::rep:CipherValue[@Id="example1"]]""" + + +data6 = """ + + + + + self::xenc:EncryptedData[@Id="example1"] + + + + +""" + +def test_6(): + rl = xenc.reference_list_from_string(data6) + assert rl + print rl + assert len(rl.data_reference) == 1 + dr = rl.data_reference[0] + assert dr.uri == "#invoice34" + assert len(dr.extension_elements) == 1 + ee = dr.extension_elements[0] + assert ee.tag == "Transforms" + assert ee.namespace == "http://www.w3.org/2000/09/xmldsig#" + trs = saml2.extension_element_to_element(ee, xmldsig.ELEMENT_FROM_STRING, + namespace=xmldsig.NAMESPACE) + + assert trs + assert len(trs.transform) == 1 + tr = trs.transform[0] + assert tr.algorithm == "http://www.w3.org/TR/1999/REC-xpath-19991116" + assert len(tr.x_path) == 1 + assert tr.x_path[0].text.strip() == """self::xenc:EncryptedData[@Id="example1"]""" + \ No newline at end of file diff --git a/tests/test_02_saml.py b/tests/test_02_saml.py new file mode 100644 index 0000000..793a49a --- /dev/null +++ b/tests/test_02_saml.py @@ -0,0 +1,998 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2010 Umeå University. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for saml2.saml""" + +__author__ = 'roland.hedberg@adm.umu.se (Roland Hedberg)' + +try: + from xml.etree import ElementTree +except ImportError: + from elementtree import ElementTree + +import saml2 +import saml2_data, ds_data + +import xmldsig as ds + +from saml2 import saml + +from py.test import raises + +class TestNameID: + + def setup_class(self): + self.name_id = saml.NameID() + + def testEmptyExtensionsList(self): + """Test if NameID has empty extensions list""" + assert isinstance(self.name_id.extension_elements, list) + assert len(self.name_id.extension_elements) == 0 + + def testFormatAttribute(self): + """Test for Format attribute accessors""" + self.name_id.format = saml.NAMEID_FORMAT_EMAILADDRESS + assert self.name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS + assert len(self.name_id.extension_elements) == 0 + new_name_id = saml.name_id_from_string(self.name_id.to_string()) + assert len(new_name_id.extension_elements) == 0 + + self.name_id.extension_elements.append(saml2.ExtensionElement( + 'foo', text='bar')) + assert len(self.name_id.extension_elements) == 1 + assert self.name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS + + def testNameIDText(self): + """Test text value of NameID element""" + self.name_id.text = "tmatsuo@example.com" + assert self.name_id.text == "tmatsuo@example.com" + + def testSPProvidedID(self): + """Test for SPProvidedID attribute accessors""" + self.name_id.sp_provided_id = "provided id" + assert self.name_id.sp_provided_id == "provided id" + + def testEmptyNameIDToAndFromStringMatch(self): + """Test name_id_from_string() with empty NameID""" + string_from_name_id = self.name_id.to_string() + new_name_id = saml.name_id_from_string(string_from_name_id) + string_from_new_name_id = new_name_id.to_string() + assert string_from_name_id == string_from_new_name_id + + def testNameIDToAndFromStringMatch(self): + """Test name_id_from_string() with data""" + self.name_id.format = saml.NAMEID_FORMAT_EMAILADDRESS + self.name_id.text = "tmatsuo@example.com" + self.name_id.name_qualifier = "name_qualifier" + self.name_id.sp_name_qualifier = "sp_name_qualifier" + string_from_name_id = self.name_id.to_string() + new_name_id = saml.name_id_from_string(string_from_name_id) + assert new_name_id.name_qualifier == "name_qualifier" + assert new_name_id.sp_name_qualifier == "sp_name_qualifier" + string_from_new_name_id = new_name_id.to_string() + assert string_from_name_id == string_from_new_name_id + + def testExtensionAttributes(self): + """Test extension attributes""" + self.name_id.extension_attributes['hoge'] = 'fuga' + self.name_id.extension_attributes['moge'] = 'muga' + assert self.name_id.extension_attributes['hoge'] == 'fuga' + assert self.name_id.extension_attributes['moge'] == 'muga' + new_name_id = saml.name_id_from_string(self.name_id.to_string()) + assert new_name_id.extension_attributes['hoge'] == 'fuga' + assert new_name_id.extension_attributes['moge'] == 'muga' + + def testname_id_from_string(self): + """Test name_id_from_string() using test data""" + name_id = saml.name_id_from_string(saml2_data.TEST_NAME_ID) + assert name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS + assert name_id.text.strip() == "tmatsuo@example.com" + assert name_id.sp_provided_id == "sp provided id" + + +class TestIssuer: + + def setup_class(self): + self.issuer = saml.Issuer() + + def testIssuerToAndFromString(self): + """Test issuer_from_string()""" + self.issuer.text = "http://www.example.com/test" + self.issuer.name_qualifier = "name_qualifier" + self.issuer.sp_name_qualifier = "sp_name_qualifier" + new_issuer = saml.issuer_from_string(self.issuer.to_string()) + assert self.issuer.text == new_issuer.text + assert self.issuer.name_qualifier == new_issuer.name_qualifier + assert self.issuer.sp_name_qualifier == new_issuer.sp_name_qualifier + assert self.issuer.extension_elements == new_issuer.extension_elements + + def testUsingTestData(self): + """Test issuer_from_string() using test data""" + issuer = saml.issuer_from_string(saml2_data.TEST_ISSUER) + assert issuer.text.strip() == "http://www.example.com/test" + new_issuer = saml.issuer_from_string(issuer.to_string()) + assert issuer.text == new_issuer.text + assert issuer.extension_elements == new_issuer.extension_elements + + +class TestSubjectLocality: + + def setup_class(self): + self.subject_locality = saml.SubjectLocality() + + def testAccessors(self): + """Test for SubjectLocality accessors""" + self.subject_locality.address = "127.0.0.1" + self.subject_locality.dns_name = "localhost" + assert self.subject_locality.address == "127.0.0.1" + assert self.subject_locality.dns_name == "localhost" + new_subject_locality = saml.subject_locality_from_string( + self.subject_locality.to_string()) + assert new_subject_locality.address == "127.0.0.1" + assert new_subject_locality.dns_name == "localhost" + + def testUsingTestData(self): + """Test SubjectLocalityFromString() using test data""" + + subject_locality = saml.subject_locality_from_string( + saml2_data.TEST_SUBJECT_LOCALITY) + assert subject_locality.address == "127.0.0.1" + assert subject_locality.dns_name == "localhost" + + new_subject_locality = saml.subject_locality_from_string( + subject_locality.to_string()) + assert new_subject_locality.address == "127.0.0.1" + assert new_subject_locality.dns_name == "localhost" + assert subject_locality.to_string() == new_subject_locality.to_string() + + +class TestAuthnContextClassRef: + + def setup_class(self): + self.authn_context_class_ref = saml.AuthnContextClassRef() + self.text = "http://www.example.com/authnContextClassRef" + + def testAccessors(self): + """Test for AuthnContextClassRef accessors""" + self.authn_context_class_ref.text = self.text + assert self.authn_context_class_ref.text == self.text + new_authn_context_class_ref = saml.authn_context_class_ref_from_string( + self.authn_context_class_ref.to_string()) + assert new_authn_context_class_ref.text == self.text + assert self.authn_context_class_ref.to_string() == \ + new_authn_context_class_ref.to_string() + + def testUsingTestData(self): + """Test authn_context_class_ref_from_string() using test data""" + authn_context_class_ref = saml.authn_context_class_ref_from_string( + saml2_data.TEST_AUTHN_CONTEXT_CLASS_REF) + assert authn_context_class_ref.text.strip() == self.text + + +class TestAuthnContextDeclRef: + + def setup_class(self): + self.authn_context_decl_ref = saml.AuthnContextDeclRef() + self.ref = "http://www.example.com/authnContextDeclRef" + + def testAccessors(self): + """Test for AuthnContextDeclRef accessors""" + self.authn_context_decl_ref.text = self.ref + assert self.authn_context_decl_ref.text == self.ref + new_authn_context_decl_ref = saml.authn_context_decl_ref_from_string( + self.authn_context_decl_ref.to_string()) + assert new_authn_context_decl_ref.text == self.ref + assert self.authn_context_decl_ref.to_string() == \ + new_authn_context_decl_ref.to_string() + + def testUsingTestData(self): + """Test authn_context_decl_ref_from_string() using test data""" + authn_context_decl_ref = saml.authn_context_decl_ref_from_string( + saml2_data.TEST_AUTHN_CONTEXT_DECL_REF) + assert authn_context_decl_ref.text.strip() == self.ref + + +class TestAuthnContextDecl: + + def setup_class(self): + self.authn_context_decl = saml.AuthnContextDecl() + self.text = "http://www.example.com/authnContextDecl" + + def testAccessors(self): + """Test for AuthnContextDecl accessors""" + self.authn_context_decl.text = self.text + assert self.authn_context_decl.text == self.text + new_authn_context_decl = saml.authn_context_decl_from_string( + self.authn_context_decl.to_string()) + assert new_authn_context_decl.text == self.text + assert self.authn_context_decl.to_string() == \ + new_authn_context_decl.to_string() + + def testUsingTestData(self): + """Test authn_context_decl_from_string() using test data""" + authn_context_decl = saml.authn_context_decl_from_string( + saml2_data.TEST_AUTHN_CONTEXT_DECL) + assert authn_context_decl.text.strip() == self.text + + +class TestAuthenticatingAuthority: + + def setup_class(self): + self.authenticating_authority = saml.AuthenticatingAuthority() + self.text = "http://www.example.com/authenticatingAuthority" + + def testAccessors(self): + """Test for AuthenticatingAuthority accessors""" + self.authenticating_authority.text = self.text + assert self.authenticating_authority.text == self.text + new_authenticating_authority = saml.authenticating_authority_from_string( + self.authenticating_authority.to_string()) + assert new_authenticating_authority.text == self.text + assert self.authenticating_authority.to_string() == \ + new_authenticating_authority.to_string() + + def testUsingTestData(self): + """Test authenticating_authority_from_string() using test data""" + authenticating_authority = saml.authenticating_authority_from_string( + saml2_data.TEST_AUTHENTICATING_AUTHORITY) + assert authenticating_authority.text.strip() == self.text + +class TestAuthnContext: + + def setup_class(self): + self.authn_context = saml.AuthnContext() + + def testAccessors(self): + """Test for AuthnContext accessors""" + self.authn_context.authn_context_class_ref = \ + saml.authn_context_class_ref_from_string( + saml2_data.TEST_AUTHN_CONTEXT_CLASS_REF) + self.authn_context.authn_context_decl_ref = \ + saml.authn_context_decl_ref_from_string( + saml2_data.TEST_AUTHN_CONTEXT_DECL_REF) + self.authn_context.authn_context_decl = \ + saml.authn_context_decl_from_string( + saml2_data.TEST_AUTHN_CONTEXT_DECL) + self.authn_context.authenticating_authority.append( + saml.authenticating_authority_from_string( + saml2_data.TEST_AUTHENTICATING_AUTHORITY)) + assert self.authn_context.authn_context_class_ref.text.strip() == \ + "http://www.example.com/authnContextClassRef" + assert self.authn_context.authn_context_decl_ref.text.strip() == \ + "http://www.example.com/authnContextDeclRef" + assert self.authn_context.authn_context_decl.text.strip() == \ + "http://www.example.com/authnContextDecl" + assert self.authn_context.authenticating_authority[0].text.strip() == \ + "http://www.example.com/authenticatingAuthority" + new_authn_context = saml.authn_context_from_string( + self.authn_context.to_string()) + assert self.authn_context.to_string() == new_authn_context.to_string() + + def testUsingTestData(self): + """Test authn_context_from_string() using test data""" + authn_context = saml.authn_context_from_string(saml2_data.TEST_AUTHN_CONTEXT) + assert authn_context.authn_context_class_ref.text.strip() == \ + saml.AUTHN_PASSWORD + + +class TestAuthnStatement: + + def setup_class(self): + self.authn_statem = saml.AuthnStatement() + + def testAccessors(self): + """Test for AuthnStatement accessors""" + self.authn_statem.authn_instant = "2007-08-31T01:05:02Z" + self.authn_statem.session_not_on_or_after = "2007-09-14T01:05:02Z" + self.authn_statem.session_index = "sessionindex" + self.authn_statem.authn_context = saml.AuthnContext() + self.authn_statem.authn_context.authn_context_class_ref = \ + saml.authn_context_class_ref_from_string( + saml2_data.TEST_AUTHN_CONTEXT_CLASS_REF) + self.authn_statem.authn_context.authn_context_decl_ref = \ + saml.authn_context_decl_ref_from_string( + saml2_data.TEST_AUTHN_CONTEXT_DECL_REF) + self.authn_statem.authn_context.authn_context_decl = \ + saml.authn_context_decl_from_string( + saml2_data.TEST_AUTHN_CONTEXT_DECL) + self.authn_statem.authn_context.authenticating_authority.append( + saml.authenticating_authority_from_string( + saml2_data.TEST_AUTHENTICATING_AUTHORITY)) + + new_as = saml.authn_statement_from_string(self.authn_statem.to_string()) + assert new_as.authn_instant == "2007-08-31T01:05:02Z" + assert new_as.session_index == "sessionindex" + assert new_as.session_not_on_or_after == "2007-09-14T01:05:02Z" + assert new_as.authn_context.authn_context_class_ref.text.strip() == \ + "http://www.example.com/authnContextClassRef" + assert new_as.authn_context.authn_context_decl_ref.text.strip() == \ + "http://www.example.com/authnContextDeclRef" + assert new_as.authn_context.authn_context_decl.text.strip() == \ + "http://www.example.com/authnContextDecl" + assert new_as.authn_context.authenticating_authority[0].text.strip() \ + == "http://www.example.com/authenticatingAuthority" + assert self.authn_statem.to_string() == new_as.to_string() + + def testUsingTestData(self): + """Test authn_statement_from_string() using test data""" + authn_statem = saml.authn_statement_from_string(saml2_data.TEST_AUTHN_STATEMENT) + assert authn_statem.authn_instant == "2007-08-31T01:05:02Z" + assert authn_statem.session_not_on_or_after == "2007-09-14T01:05:02Z" + assert authn_statem.authn_context.authn_context_class_ref.text.strip() == \ + saml.AUTHN_PASSWORD + + +class TestAttributeValue: + + def setup_class(self): + self.attribute_value = saml.AttributeValue() + self.text = "value for test attribute" + + def testAccessors(self): + """Test for AttributeValue accessors""" + + self.attribute_value.text = self.text + new_attribute_value = saml.attribute_value_from_string( + self.attribute_value.to_string()) + assert new_attribute_value.text.strip() == self.text + + def testUsingTestData(self): + """Test attribute_value_from_string() using test data""" + + attribute_value = saml.attribute_value_from_string( + saml2_data.TEST_ATTRIBUTE_VALUE) + assert attribute_value.text.strip() == self.text + +BASIC_STR_AV = """ + +By-Tor +""" + +BASIC_INT_AV = """ + +23 +""" + +BASIC_NOT_INT_AV = """ + +foo +""" + +BASIC_BOOLEAN_TRUE_AV = """ + +true +""" + +BASIC_BOOLEAN_FALSE_AV = """ + +false +""" + +BASIC_BASE64_AV = """ + +VU5JTkVUVA== +""" + +X500_AV = """ + +Steven + +""" + +UUID_AV = """ + +1 +""" + +class TestAttribute: + + def setup_class(self): + self.attribute = saml.Attribute() + self.text = ["value of test attribute", + "value1 of test attribute", + "value2 of test attribute"] + + def testAccessors(self): + """Test for Attribute accessors""" + self.attribute.name = "testAttribute" + self.attribute.name_format = saml.NAME_FORMAT_URI + self.attribute.friendly_name = "test attribute" + self.attribute.attribute_value.append(saml.AttributeValue()) + self.attribute.attribute_value[0].text = self.text[0] + + new_attribute = saml.attribute_from_string(self.attribute.to_string()) + assert new_attribute.name == "testAttribute" + assert new_attribute.name_format == saml.NAME_FORMAT_URI + assert new_attribute.friendly_name == "test attribute" + assert new_attribute.attribute_value[0].text.strip() == self.text[0] + + def testUsingTestData(self): + """Test attribute_from_string() using test data""" + attribute = saml.attribute_from_string(saml2_data.TEST_ATTRIBUTE) + assert attribute.name == "testAttribute" + assert attribute.name_format == saml.NAME_FORMAT_UNSPECIFIED + assert attribute.friendly_name == "test attribute" + assert attribute.attribute_value[0].text.strip() == self.text[1] + assert attribute.attribute_value[1].text.strip() == self.text[2] + # test again + attribute = saml.attribute_from_string(attribute.to_string()) + assert attribute.name == "testAttribute" + assert attribute.name_format == saml.NAME_FORMAT_UNSPECIFIED + assert attribute.friendly_name == "test attribute" + assert attribute.attribute_value[0].text.strip() == self.text[1] + assert attribute.attribute_value[1].text.strip() == self.text[2] + + def test_basic_str(self): + attribute = saml.attribute_from_string(BASIC_STR_AV) + print attribute + assert attribute.attribute_value[0].text.strip() == "By-Tor" + + def test_basic_int(self): + attribute = saml.attribute_from_string(BASIC_INT_AV) + print attribute + assert attribute.attribute_value[0].text == "23" + + def test_basic_not_int(self): + # attr = saml.attribute_from_string(BASIC_NOT_INT_AV) + # print attr.__dict__.keys() + # print attr.attribute_value[0].__dict__.keys() + # print attr.attribute_value[0].type + # print attr.attribute_value[0].extension_attributes + # print attr + raises(ValueError, "saml.attribute_from_string(BASIC_NOT_INT_AV)") + + def test_basic_base64(self): + attribute = saml.attribute_from_string(BASIC_BASE64_AV) + print attribute + assert attribute.attribute_value[0].text == "VU5JTkVUVA==" + assert attribute.attribute_value[0].get_type() == "xs:base64Binary" + + def test_basic_boolean_true(self): + attribute = saml.attribute_from_string(BASIC_BOOLEAN_TRUE_AV) + print attribute + assert attribute.attribute_value[0].text.lower() == "true" + + def test_basic_boolean_false(self): + attribute = saml.attribute_from_string(BASIC_BOOLEAN_FALSE_AV) + print attribute + assert attribute.attribute_value[0].text.lower() == "false" + +class TestAttributeStatement: + + def setup_class(self): + self.attr_statem = saml.AttributeStatement() + self.text = ["value of test attribute", + "value1 of test attribute", + "value2 of test attribute", + "value1 of test attribute2", + "value2 of test attribute2",] + + def testAccessors(self): + """Test for Attribute accessors""" + self.attr_statem.attribute.append(saml.Attribute()) + self.attr_statem.attribute.append(saml.Attribute()) + self.attr_statem.attribute[0].name = "testAttribute" + self.attr_statem.attribute[0].name_format = saml.NAME_FORMAT_URI + self.attr_statem.attribute[0].friendly_name = "test attribute" + self.attr_statem.attribute[0].attribute_value.append(saml.AttributeValue()) + self.attr_statem.attribute[0].attribute_value[0].text = self.text[0] + + self.attr_statem.attribute[1].name = "testAttribute2" + self.attr_statem.attribute[1].name_format = saml.NAME_FORMAT_UNSPECIFIED + self.attr_statem.attribute[1].friendly_name = self.text[2] + self.attr_statem.attribute[1].attribute_value.append(saml.AttributeValue()) + self.attr_statem.attribute[1].attribute_value[0].text = self.text[2] + + new_as = saml.attribute_statement_from_string(self.attr_statem.to_string()) + assert new_as.attribute[0].name == "testAttribute" + assert new_as.attribute[0].name_format == saml.NAME_FORMAT_URI + assert new_as.attribute[0].friendly_name == "test attribute" + assert new_as.attribute[0].attribute_value[0].text.strip() == self.text[0] + assert new_as.attribute[1].name == "testAttribute2" + assert new_as.attribute[1].name_format == saml.NAME_FORMAT_UNSPECIFIED + assert new_as.attribute[1].friendly_name == "value2 of test attribute" + assert new_as.attribute[1].attribute_value[0].text.strip() == self.text[2] + + def testUsingTestData(self): + """Test attribute_statement_from_string() using test data""" + attr_statem = saml.attribute_statement_from_string( \ + saml2_data.TEST_ATTRIBUTE_STATEMENT) + assert attr_statem.attribute[0].name == "testAttribute" + assert attr_statem.attribute[0].name_format == saml.NAME_FORMAT_UNSPECIFIED + assert attr_statem.attribute[0].friendly_name == "test attribute" + assert attr_statem.attribute[0].attribute_value[0].text.strip() == self.text[1] + assert attr_statem.attribute[0].attribute_value[1].text.strip() == self.text[2] + assert attr_statem.attribute[1].name == "http://www.example.com/testAttribute2" + assert attr_statem.attribute[1].name_format == saml.NAME_FORMAT_URI + assert attr_statem.attribute[1].friendly_name == "test attribute2" + assert attr_statem.attribute[1].attribute_value[0].text.strip() == self.text[3] + assert attr_statem.attribute[1].attribute_value[1].text.strip() == self.text[4] + + # test again + attr_statem2 = saml.attribute_statement_from_string(attr_statem.to_string()) + assert attr_statem2.attribute[0].name == "testAttribute" + assert attr_statem2.attribute[0].name_format == saml.NAME_FORMAT_UNSPECIFIED + assert attr_statem2.attribute[0].friendly_name == "test attribute" + assert attr_statem2.attribute[0].attribute_value[0].text.strip() == self.text[1] + assert attr_statem2.attribute[0].attribute_value[1].text.strip() == self.text[2] + assert attr_statem2.attribute[1].name == "http://www.example.com/testAttribute2" + assert attr_statem2.attribute[1].name_format == saml.NAME_FORMAT_URI + assert attr_statem2.attribute[1].friendly_name == "test attribute2" + assert attr_statem2.attribute[1].attribute_value[0].text.strip() == self.text[3] + assert attr_statem2.attribute[1].attribute_value[1].text.strip() == self.text[4] + + +class TestSubjectConfirmationData: + + def setup_class(self): + self.scd = saml.SubjectConfirmationData() + + def testAccessors(self): + """Test for SubjectConfirmationData accessors""" + + self.scd.not_before = "2007-08-31T01:05:02Z" + self.scd.not_on_or_after = "2007-09-14T01:05:02Z" + self.scd.recipient = "recipient" + self.scd.in_response_to = "responseID" + self.scd.address = "127.0.0.1" + new_scd = saml.subject_confirmation_data_from_string(self.scd.to_string()) + assert new_scd.not_before == "2007-08-31T01:05:02Z" + assert new_scd.not_on_or_after == "2007-09-14T01:05:02Z" + assert new_scd.recipient == "recipient" + assert new_scd.in_response_to == "responseID" + assert new_scd.address == "127.0.0.1" + + def testUsingTestData(self): + """Test subject_confirmation_data_from_string() using test data""" + + scd = saml.subject_confirmation_data_from_string( + saml2_data.TEST_SUBJECT_CONFIRMATION_DATA) + assert scd.not_before == "2007-08-31T01:05:02Z" + assert scd.not_on_or_after == "2007-09-14T01:05:02Z" + assert scd.recipient == "recipient" + assert scd.in_response_to == "responseID" + assert scd.address == "127.0.0.1" + + +class TestSubjectConfirmation: + + def setup_class(self): + self.sc = saml.SubjectConfirmation() + + def testAccessors(self): + """Test for SubjectConfirmation accessors""" + self.sc.name_id = saml.name_id_from_string(saml2_data.TEST_NAME_ID) + self.sc.method = saml.SUBJECT_CONFIRMATION_METHOD_BEARER + self.sc.subject_confirmation_data = saml.subject_confirmation_data_from_string( + saml2_data.TEST_SUBJECT_CONFIRMATION_DATA) + new_sc = saml.subject_confirmation_from_string(self.sc.to_string()) + assert new_sc.name_id.sp_provided_id == "sp provided id" + assert new_sc.method == saml.SUBJECT_CONFIRMATION_METHOD_BEARER + assert new_sc.subject_confirmation_data.not_before == \ + "2007-08-31T01:05:02Z" + assert new_sc.subject_confirmation_data.not_on_or_after == \ + "2007-09-14T01:05:02Z" + assert new_sc.subject_confirmation_data.recipient == "recipient" + assert new_sc.subject_confirmation_data.in_response_to == "responseID" + assert new_sc.subject_confirmation_data.address == "127.0.0.1" + + def testUsingTestData(self): + """Test subject_confirmation_from_string() using test data""" + + sc = saml.subject_confirmation_from_string( + saml2_data.TEST_SUBJECT_CONFIRMATION) + assert sc.name_id.sp_provided_id == "sp provided id" + assert sc.method == saml.SUBJECT_CONFIRMATION_METHOD_BEARER + assert sc.subject_confirmation_data.not_before == "2007-08-31T01:05:02Z" + assert sc.subject_confirmation_data.not_on_or_after == "2007-09-14T01:05:02Z" + assert sc.subject_confirmation_data.recipient == "recipient" + assert sc.subject_confirmation_data.in_response_to == "responseID" + assert sc.subject_confirmation_data.address == "127.0.0.1" + + +class TestSubject: + + def setup_class(self): + self.subject = saml.Subject() + + def testAccessors(self): + """Test for Subject accessors""" + self.subject.name_id = saml.name_id_from_string(saml2_data.TEST_NAME_ID) + self.subject.subject_confirmation.append( + saml.subject_confirmation_from_string( + saml2_data.TEST_SUBJECT_CONFIRMATION)) + new_subject = saml.subject_from_string(self.subject.to_string()) + assert new_subject.name_id.sp_provided_id == "sp provided id" + assert new_subject.name_id.text.strip() == "tmatsuo@example.com" + assert new_subject.name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS + assert isinstance(new_subject.subject_confirmation[0], + saml.SubjectConfirmation) + + def testUsingTestData(self): + """Test for subject_from_string() using test data.""" + + subject = saml.subject_from_string(saml2_data.TEST_SUBJECT) + assert subject.name_id.sp_provided_id == "sp provided id" + assert subject.name_id.text.strip() == "tmatsuo@example.com" + assert subject.name_id.format == saml.NAMEID_FORMAT_EMAILADDRESS + assert isinstance(subject.subject_confirmation[0], + saml.SubjectConfirmation) + + +class TestCondition: + + def setup_class(self): + self.condition = saml.Condition() + self.name = "{%s}type" % saml.XSI_NAMESPACE + + def testAccessors(self): + """Test for Condition accessors.""" + self.condition.extension_attributes[self.name] = "test" + self.condition.extension_attributes['ExtendedAttribute'] = "value" + new_condition = saml.condition_from_string(self.condition.to_string()) + assert new_condition.extension_attributes[self.name] == "test" + assert new_condition.extension_attributes["ExtendedAttribute"] == "value" + + def testUsingTestData(self): + """Test for condition_from_string() using test data.""" + condition = saml.condition_from_string(saml2_data.TEST_CONDITION) + assert condition.extension_attributes[self.name] == "test" + assert condition.extension_attributes["ExtendedAttribute"] == "value" + + +class TestAudience: + + def setup_class(self): + self.audience = saml.Audience() + + def testAccessors(self): + """Test for Audience accessors""" + + self.audience.text = "http://www.example.com/Audience" + new_audience = saml.audience_from_string(self.audience.to_string()) + assert new_audience.text.strip() == "http://www.example.com/Audience" + + def testUsingTestData(self): + """Test audience_from_string using test data""" + + audience = saml.audience_from_string(saml2_data.TEST_AUDIENCE) + assert audience.text.strip() == "http://www.example.com/Audience" + + +class TestAudienceRestriction: + def setup_class(self): + self.audience_restriction = saml.AudienceRestriction() + + def testAccessors(self): + """Test for AudienceRestriction accessors""" + + self.audience_restriction.audience = \ + saml.audience_from_string(saml2_data.TEST_AUDIENCE) + new_audience = saml.audience_restriction_from_string( + self.audience_restriction.to_string()) + assert self.audience_restriction.audience.text.strip() == \ + "http://www.example.com/Audience" + + def testUsingTestData(self): + """Test audience_restriction_from_string using test data""" + + audience_restriction = saml.audience_restriction_from_string( + saml2_data.TEST_AUDIENCE_RESTRICTION) + assert audience_restriction.audience[0].text.strip() == \ + "http://www.example.com/Audience" + + +class TestOneTimeUse: + + def setup_class(self): + self.one_time_use = saml.OneTimeUse() + + def testAccessors(self): + """Test for OneTimeUse accessors""" + assert isinstance(self.one_time_use, saml.OneTimeUse) + assert isinstance(self.one_time_use, saml.ConditionAbstractType) + + def testUsingTestData(self): + """Test one_time_use_from_string() using test data""" + one_time_use = saml.one_time_use_from_string(saml2_data.TEST_ONE_TIME_USE) + assert isinstance(one_time_use, saml.OneTimeUse) + assert isinstance(one_time_use, saml.ConditionAbstractType) + + +class TestProxyRestriction: + + def setup_class(self): + self.proxy_restriction = saml.ProxyRestriction() + + def testAccessors(self): + """Test for ProxyRestriction accessors""" + + assert isinstance(self.proxy_restriction, saml.ConditionAbstractType) + self.proxy_restriction.count = "2" + self.proxy_restriction.audience.append(saml.audience_from_string( + saml2_data.TEST_AUDIENCE)) + new_proxy_restriction = saml.proxy_restriction_from_string( + self.proxy_restriction.to_string()) + assert new_proxy_restriction.count == "2" + assert new_proxy_restriction.audience[0].text.strip() == \ + "http://www.example.com/Audience" + + def testUsingTestData(self): + """Test proxy_restriction_from_string() using test data""" + + proxy_restriction = saml.proxy_restriction_from_string( + saml2_data.TEST_PROXY_RESTRICTION) + assert proxy_restriction.count == "2" + assert proxy_restriction.audience[0].text.strip() == \ + "http://www.example.com/Audience" + +class TestConditions: + + def setup_class(self): + self.conditions = saml.Conditions() + + def testAccessors(self): + """Test for Conditions accessors""" + self.conditions.not_before = "2007-08-31T01:05:02Z" + self.conditions.not_on_or_after = "2007-09-14T01:05:02Z" + self.conditions.condition.append(saml.Condition()) + self.conditions.audience_restriction.append(saml.AudienceRestriction()) + self.conditions.one_time_use.append(saml.OneTimeUse()) + self.conditions.proxy_restriction.append(saml.ProxyRestriction()) + new_conditions = saml.conditions_from_string(self.conditions.to_string()) + assert new_conditions.not_before == "2007-08-31T01:05:02Z" + assert new_conditions.not_on_or_after == "2007-09-14T01:05:02Z" + assert isinstance(new_conditions.condition[0], saml.Condition) + assert isinstance(new_conditions.audience_restriction[0], + saml.AudienceRestriction) + assert isinstance(new_conditions.one_time_use[0], + saml.OneTimeUse) + assert isinstance(new_conditions.proxy_restriction[0], + saml.ProxyRestriction) + + def testUsingTestData(self): + """Test conditions_from_string() using test data""" + new_conditions = saml.conditions_from_string(saml2_data.TEST_CONDITIONS) + assert new_conditions.not_before == "2007-08-31T01:05:02Z" + assert new_conditions.not_on_or_after == "2007-09-14T01:05:02Z" + assert isinstance(new_conditions.condition[0], saml.Condition) + assert isinstance(new_conditions.audience_restriction[0], + saml.AudienceRestriction) + assert isinstance(new_conditions.one_time_use[0], + saml.OneTimeUse) + assert isinstance(new_conditions.proxy_restriction[0], + saml.ProxyRestriction) + +class TestAssertionIDRef: + + def setup_class(self): + self.assertion_id_ref = saml.AssertionIDRef() + + def testAccessors(self): + """Test for AssertionIDRef accessors""" + self.assertion_id_ref.text = "zzlieajngjbkjggjldmgindkckkolcblndbghlhm" + new_assertion_id_ref = saml.assertion_id_ref_from_string( + self.assertion_id_ref.to_string()) + assert new_assertion_id_ref.text == \ + "zzlieajngjbkjggjldmgindkckkolcblndbghlhm" + + def testUsingTestData(self): + """Test assertion_id_ref_from_string() using test data""" + new_assertion_id_ref = saml.assertion_id_ref_from_string( + saml2_data.TEST_ASSERTION_ID_REF) + assert new_assertion_id_ref.text.strip() == \ + "zzlieajngjbkjggjldmgindkckkolcblndbghlhm" + + +class TestAssertionURIRef: + + def setup_class(self): + self.assertion_uri_ref = saml.AssertionURIRef() + + def testAccessors(self): + """Test for AssertionURIRef accessors""" + self.assertion_uri_ref.text = "http://www.example.com/AssertionURIRef" + new_assertion_uri_ref = saml.assertion_uri_ref_from_string( + self.assertion_uri_ref.to_string()) + assert new_assertion_uri_ref.text == \ + "http://www.example.com/AssertionURIRef" + + def testUsingTestData(self): + """Test assertion_uri_ref_from_string() using test data""" + new_assertion_uri_ref = saml.assertion_uri_ref_from_string( + saml2_data.TEST_ASSERTION_URI_REF) + assert new_assertion_uri_ref.text.strip() == \ + "http://www.example.com/AssertionURIRef" + + +class TestAction: + + def setup_class(self): + self.action = saml.Action() + + def testAccessors(self): + """Test for Action accessors""" + self.action.namespace = "http://www.example.com/Namespace" + new_action = saml.action_from_string(self.action.to_string()) + assert new_action.namespace == "http://www.example.com/Namespace" + + def testUsingTestData(self): + """Test action_from_string() using test data""" + new_action = saml.action_from_string(saml2_data.TEST_ACTION) + assert new_action.namespace == "http://www.example.com/Namespace" + + +class TestEvidence: + + def setup_class(self): + self.evidence = saml.Evidence() + + def testAccessors(self): + """Test for Evidence accessors""" + self.evidence.assertion_id_ref.append(saml.AssertionIDRef()) + self.evidence.assertion_uri_ref.append(saml.AssertionURIRef()) + self.evidence.assertion.append(saml.Assertion()) + self.evidence.encrypted_assertion.append(saml.EncryptedAssertion()) + new_evidence = saml.evidence_from_string(self.evidence.to_string()) + print new_evidence + assert self.evidence.to_string() == new_evidence.to_string() + assert isinstance(new_evidence.assertion_id_ref[0], + saml.AssertionIDRef) + assert isinstance(new_evidence.assertion_uri_ref[0], + saml.AssertionURIRef) + assert len(new_evidence.assertion) == 1 + assert isinstance(new_evidence.assertion[0], saml.Assertion) + assert len(new_evidence.encrypted_assertion) == 1 + assert isinstance(new_evidence.encrypted_assertion[0], + saml.EncryptedAssertion) + + def testUsingTestData(self): + """Test evidence_from_string() using test data""" + # TODO: + pass + + +class TestAuthzDecisionStatement: + + def setup_class(self): + self.authz_decision_statement = saml.AuthzDecisionStatement() + + def testAccessors(self): + """Test for AuthzDecisionStatement accessors""" + self.authz_decision_statement.resource = "http://www.example.com/Resource" + self.authz_decision_statement.decision = saml.DECISION_TYPE_PERMIT + self.authz_decision_statement.action.append(saml.Action()) + self.authz_decision_statement.evidence = saml.Evidence() + new_authz_decision_statement = saml.authz_decision_statement_from_string( + self.authz_decision_statement.to_string()) + assert self.authz_decision_statement.to_string() == \ + new_authz_decision_statement.to_string() + assert new_authz_decision_statement.resource == \ + "http://www.example.com/Resource" + assert new_authz_decision_statement.decision == \ + saml.DECISION_TYPE_PERMIT + assert isinstance(new_authz_decision_statement.action[0], + saml.Action) + assert isinstance(new_authz_decision_statement.evidence, + saml.Evidence) + + + def testUsingTestData(self): + """Test authz_decision_statement_from_string() using test data""" + # TODO: + pass + +class TestAdvice: + + def setup_class(self): + self.advice = saml.Advice() + + def testAccessors(self): + """Test for Advice accessors""" + self.advice.assertion_id_ref.append(saml.AssertionIDRef()) + self.advice.assertion_uri_ref.append(saml.AssertionURIRef()) + self.advice.assertion.append(saml.Assertion()) + self.advice.encrypted_assertion.append(saml.EncryptedAssertion()) + new_advice = saml.advice_from_string(self.advice.to_string()) + assert self.advice.to_string() == new_advice.to_string() + assert isinstance(new_advice.assertion_id_ref[0], + saml.AssertionIDRef) + assert isinstance(new_advice.assertion_uri_ref[0], + saml.AssertionURIRef) + assert isinstance(new_advice.assertion[0], saml.Assertion) + assert isinstance(new_advice.encrypted_assertion[0], + saml.EncryptedAssertion) + + def testUsingTestData(self): + """Test advice_from_string() using test data""" + # TODO: + pass + + +class TestAssertion: + + def setup_class(self): + self.assertion = saml.Assertion() + + def testAccessors(self): + """Test for Assertion accessors""" + self.assertion.id = "assertion id" + self.assertion.version = saml2.VERSION + self.assertion.issue_instant = "2007-08-31T01:05:02Z" + self.assertion.issuer = saml.issuer_from_string(saml2_data.TEST_ISSUER) + self.assertion.signature = ds.signature_from_string( + ds_data.TEST_SIGNATURE) + self.assertion.subject = saml.subject_from_string(saml2_data.TEST_SUBJECT) + self.assertion.conditions = saml.conditions_from_string( + saml2_data.TEST_CONDITIONS) + self.assertion.advice = saml.Advice() + self.assertion.statement.append(saml.Statement()) + self.assertion.authn_statement.append(saml.authn_statement_from_string( + saml2_data.TEST_AUTHN_STATEMENT)) + self.assertion.authz_decision_statement.append( + saml.AuthzDecisionStatement()) + self.assertion.attribute_statement.append( + saml.attribute_statement_from_string( + saml2_data.TEST_ATTRIBUTE_STATEMENT)) + + new_assertion = saml.assertion_from_string(self.assertion.to_string()) + assert new_assertion.id == "assertion id" + assert new_assertion.version == saml2.VERSION + assert new_assertion.issue_instant == "2007-08-31T01:05:02Z" + assert isinstance(new_assertion.issuer, saml.Issuer) + assert isinstance(new_assertion.signature, ds.Signature) + assert isinstance(new_assertion.subject, saml.Subject) + assert isinstance(new_assertion.conditions, saml.Conditions) + assert isinstance(new_assertion.advice, saml.Advice) + assert isinstance(new_assertion.statement[0], saml.Statement) + assert isinstance(new_assertion.authn_statement[0], + saml.AuthnStatement) + assert isinstance(new_assertion.authz_decision_statement[0], + saml.AuthzDecisionStatement) + assert isinstance(new_assertion.attribute_statement[0], + saml.AttributeStatement) + + + def testUsingTestData(self): + """Test assertion_from_string() using test data""" + # TODO + pass diff --git a/tests/test_03_saml2.py b/tests/test_03_saml2.py new file mode 100644 index 0000000..ebac945 --- /dev/null +++ b/tests/test_03_saml2.py @@ -0,0 +1,524 @@ +#!/usr/bin/env python + +import saml2 + +from saml2 import create_class_from_xml_string, class_name, make_vals, md +from saml2.saml import NameID, Issuer, SubjectLocality, AuthnContextClassRef +from saml2.saml import SubjectConfirmationData, SubjectConfirmation +from saml2.saml import Attribute + +from py.test import raises +import saml2_data + +try: + from xml.etree import cElementTree as ElementTree +except ImportError: + try: + import cElementTree as ElementTree + except ImportError: + from elementtree import ElementTree + +ITEMS = { + NameID:[""" + + roland@example.com + +""", """ +_1632879f09d08ea5ede2dc667cbed7e429ebc4335c +""", """ +test +"""], + Issuer:""" + + http://www.example.com/test + +""", + SubjectLocality: """ + +""", + SubjectConfirmationData: +""" +""", + SubjectConfirmation: + """ +test@example.com + +""" +} + +#def pytest_generate_tests(metafunc): +# if "target_class" in metafunc.funcargnames: +# for tcl,xml in ITEMS.items(): +# metafunc.addcall(funcargs={"target_class":tcl,"xml_string":xml}) + +def _eq(l1,l2): + return set(l1) == set(l2) + +def test_create_class_from_xml_string_nameid(): + kl = create_class_from_xml_string(NameID, ITEMS[NameID][0]) + assert kl != None + assert kl.format == "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" + assert kl.sp_provided_id == "sp provided id" + assert kl.text.strip() == "roland@example.com" + assert _eq(kl.keyswv(), ['sp_provided_id', 'format', 'text']) + assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:NameID" + assert _eq(kl.keys(), ['sp_provided_id', 'sp_name_qualifier', + 'name_qualifier', 'format', 'text']) + + kl = create_class_from_xml_string(NameID, ITEMS[NameID][1]) + assert kl != None + assert kl.format == "urn:oasis:names:tc:SAML:2.0:nameid-format:transient" + assert kl.sp_name_qualifier == "https://foo.example.com/sp" + assert kl.text.strip() == "_1632879f09d08ea5ede2dc667cbed7e429ebc4335c" + assert _eq(kl.keyswv(), ['sp_name_qualifier', 'format', 'text']) + assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:NameID" + + kl = create_class_from_xml_string(NameID, ITEMS[NameID][2]) + assert kl != None + assert kl.format == "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" + assert kl.name_qualifier == "http://authentic.example.com/saml/metadata" + assert kl.sp_name_qualifier == "http://auth.example.com/saml/metadata" + assert kl.text.strip() == "test" + assert _eq(kl.keyswv(), ['sp_name_qualifier', 'format', 'name_qualifier', + 'text']) + assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:NameID" + +def test_create_class_from_xml_string_issuer(): + kl = create_class_from_xml_string(Issuer, ITEMS[Issuer]) + assert kl != None + assert kl.text.strip() == "http://www.example.com/test" + assert _eq(kl.keyswv(), ['text']) + assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:Issuer" + +def test_create_class_from_xml_string_subject_locality(): + kl = create_class_from_xml_string(SubjectLocality, ITEMS[SubjectLocality]) + assert kl != None + assert _eq(kl.keyswv(), ['address', "dns_name"]) + assert kl.address == "127.0.0.1" + assert kl.dns_name == "localhost" + assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality" + +def test_create_class_from_xml_string_subject_confirmation_data(): + kl = create_class_from_xml_string(SubjectConfirmationData, + ITEMS[SubjectConfirmationData]) + assert kl != None + assert _eq(kl.keyswv(), ['in_response_to', 'not_on_or_after', + 'not_before', 'recipient']) + assert kl.in_response_to == "_1683146e27983964fbe7bf8f08961108d166a652e5" + assert kl.not_on_or_after == "2010-02-18T13:52:13.959Z" + assert kl.not_before == "2010-01-16T12:00:00Z" + assert kl.recipient == "http://192.168.0.10/saml/sp" + assert class_name(kl) == \ + "urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData" + +def test_create_class_from_xml_string_subject_confirmation(): + kl = create_class_from_xml_string(SubjectConfirmation, + ITEMS[SubjectConfirmation]) + assert kl != None + assert _eq(kl.keyswv(), ['method', 'name_id', + 'subject_confirmation_data']) + assert kl.method == "urn:oasis:names:tc:SAML:2.0:cm:bearer" + name_id = kl.name_id + assert _eq(name_id.keyswv(), ['format', 'name_qualifier', 'text']) + assert name_id.format == "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" + assert name_id.name_qualifier == "http://authentic.example.com/saml/metadata" + assert name_id.text.strip() == "test@example.com" + subject_confirmation_data = kl.subject_confirmation_data + assert _eq(subject_confirmation_data.keyswv(), ['not_on_or_after', + 'recipient', 'in_response_to']) + assert subject_confirmation_data.recipient == \ + "http://auth.example.com/saml/proxySingleSignOnRedirect" + assert subject_confirmation_data.not_on_or_after == "2010-02-17T17:02:38Z" + assert subject_confirmation_data.in_response_to == \ + "_59B3A01B03334032C31E434C63F89E3E" + assert class_name(kl) == \ + "urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation" + +def test_create_class_from_xml_string_wrong_class_spec(): + kl = create_class_from_xml_string(SubjectConfirmationData, + ITEMS[SubjectConfirmation]) + assert kl == None + +def test_ee_1(): + ee = saml2.extension_element_from_string( + """bar""") + assert ee != None + print ee.__dict__ + assert ee.attributes == {} + assert ee.tag == "foo" + assert ee.namespace == None + assert ee.children == [] + assert ee.text == "bar" + +def test_ee_2(): + ee = saml2.extension_element_from_string( + """bar""") + assert ee != None + print ee.__dict__ + assert ee.attributes == {"id":"xyz"} + assert ee.tag == "foo" + assert ee.namespace == None + assert ee.children == [] + assert ee.text == "bar" + +def test_ee_3(): + ee = saml2.extension_element_from_string( + """ + bar""") + assert ee != None + print ee.__dict__ + assert ee.attributes == {"id":"xyz"} + assert ee.tag == "foo" + assert ee.namespace == "urn:mace:example.com:saml:ns" + assert ee.children == [] + assert ee.text == "bar" + +def test_ee_4(): + ee = saml2.extension_element_from_string( + """ + + xyztre""") + assert ee != None + print ee.__dict__ + assert ee.attributes == {} + assert ee.tag == "foo" + assert ee.namespace == "urn:mace:example.com:saml:ns" + assert len(ee.children) == 2 + assert ee.text.strip() == "" + id = ee.find_children("id", "urn:mace:example.com:saml:namespace") + assert id == [] + ids = ee.find_children("id", "urn:mace:example.com:saml:ns") + assert ids != [] + id = ids[0] + print id.__dict__ + assert id.attributes == {} + assert id.tag == "id" + assert id.namespace == "urn:mace:example.com:saml:ns" + assert id.children == [] + assert id.text.strip() == "xyz" + +def test_ee_5(): + ee = saml2.extension_element_from_string( + """ + bar""") + + ce = saml2.extension_element_from_string( + """ + rev""") + + ee.children.append(ce) + + assert ee != None + print ee.__dict__ + assert ee.attributes == {} + assert ee.tag == "foo" + assert ee.namespace == "urn:mace:example.com:saml:ns" + assert len(ee.children) == 1 + assert ee.text.strip() == "bar" + + c = ee.children[0] + print c.__dict__ + + child = ee.find_children(namespace="urn:mace:example.com:saml:cu") + assert len(child) == 1 + child = ee.find_children(namespace="urn:mace:example.com:saml:ns") + assert len(child) == 0 + child = ee.find_children("educause","urn:mace:example.com:saml:cu") + assert len(child) == 1 + child = ee.find_children("edugain","urn:mace:example.com:saml:cu") + assert len(child) == 0 + print ee.to_string() + +def test_ee_6(): + ee = saml2.extension_element_from_string( + """ + bar""") + + ce = saml2.extension_element_from_string( + """ + rev""") + + et = ee.transfer_to_element_tree() + ce.become_child_element_of(et) + + pee = saml2._extension_element_from_element_tree(et) + + assert pee != None + print pee.__dict__ + assert pee.attributes == {} + assert pee.tag == "foo" + assert pee.namespace == "urn:mace:example.com:saml:ns" + assert len(pee.children) == 1 + assert pee.text.strip() == "bar" + + c = pee.children[0] + print c.__dict__ + + child = pee.find_children(namespace="urn:mace:example.com:saml:cu") + assert len(child) == 1 + child = pee.find_children(namespace="urn:mace:example.com:saml:ns") + assert len(child) == 0 + child = pee.find_children("educause","urn:mace:example.com:saml:cu") + assert len(child) == 1 + child = pee.find_children("edugain","urn:mace:example.com:saml:cu") + assert len(child) == 0 + print pee.to_string() + + +NAMEID_WITH_ATTRIBUTE_EXTENSION = """ + + roland@example.com + +""" + +def test_nameid_with_extension(): + kl = create_class_from_xml_string(NameID, NAMEID_WITH_ATTRIBUTE_EXTENSION) + assert kl != None + print kl.__dict__ + assert kl.format == "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" + assert kl.sp_provided_id == "sp provided id" + assert kl.text.strip() == "roland@example.com" + assert _eq(kl.keyswv(), ['sp_provided_id', 'format', + 'extension_attributes', 'text']) + assert class_name(kl) == "urn:oasis:names:tc:SAML:2.0:assertion:NameID" + assert _eq(kl.keys(), ['sp_provided_id', 'sp_name_qualifier', + 'name_qualifier', 'format', 'text']) + assert kl.extension_attributes == { + '{urn:mace:example.com:saml:assertion}Foo': 'BAR'} + +SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION = """ + +test@example.com + + + +Excellent + +""" + +def test_subject_confirmation_with_extension(): + kl = create_class_from_xml_string(SubjectConfirmation, + SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION) + assert kl != None + print kl.__dict__ + assert kl.extension_attributes == {} + assert kl.method == "urn:oasis:names:tc:SAML:2.0:cm:bearer" + name_id = kl.name_id + assert _eq(name_id.keyswv(), ['format', 'name_qualifier', 'text']) + assert name_id.format == "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" + assert name_id.name_qualifier == "http://authentic.example.com/saml/metadata" + assert name_id.text.strip() == "test@example.com" + subject_confirmation_data = kl.subject_confirmation_data + assert _eq(subject_confirmation_data.keyswv(), ['not_on_or_after', + 'recipient', 'in_response_to']) + assert subject_confirmation_data.recipient == \ + "http://auth.example.com/saml/proxySingleSignOnRedirect" + assert subject_confirmation_data.not_on_or_after == "2010-02-17T17:02:38Z" + assert subject_confirmation_data.in_response_to == \ + "_59B3A01B03334032C31E434C63F89E3E" + assert len(kl.extension_elements) == 1 + ee = kl.extension_elements[0] + assert ee.tag == "Trustlevel" + assert ee.namespace == "urn:mace:example.com:saml:assertion" + assert ee.text.strip() == "Excellent" + +def test_to_fro_string_1(): + kl = create_class_from_xml_string(SubjectConfirmation, + SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION) + str = kl.to_string() + cpy = create_class_from_xml_string(SubjectConfirmation, str) + + print kl.__dict__ + print cpy.__dict__ + + assert kl.text.strip() == cpy.text.strip() + assert _eq(kl.keyswv(), cpy.keyswv()) + assert len(kl.extension_elements) == len(cpy.extension_elements) + klee = kl.extension_elements[0] + cpyee = cpy.extension_elements[0] + assert klee.text.strip() == cpyee.text.strip() + assert klee.tag == cpyee.tag + assert klee.namespace == cpyee.namespace + + +def test_make_vals_str(): + kl = make_vals("Jeter",md.GivenName, part=True) + assert isinstance(kl, md.GivenName) + assert kl.text == "Jeter" + +def test_make_vals_list_of_strs(): + cp = md.ContactPerson() + make_vals(["Derek","Sanderson"], md.GivenName, cp, "given_name") + assert len(cp.given_name) == 2 + assert _eq([i.text for i in cp.given_name],["Sanderson","Derek"]) + +def test_attribute_element_to_extension_element(): + attr = create_class_from_xml_string(Attribute, saml2_data.TEST_ATTRIBUTE) + ee = saml2.element_to_extension_element(attr) + print ee.__dict__ + assert ee.tag == "Attribute" + assert ee.namespace == 'urn:oasis:names:tc:SAML:2.0:assertion' + assert _eq(ee.attributes.keys(),['FriendlyName', 'Name', 'NameFormat']) + assert ee.attributes["FriendlyName"] == 'test attribute' + assert ee.attributes["Name"] == "testAttribute" + assert ee.attributes["NameFormat"] == \ + 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified' + assert len(ee.children) == 2 + for child in ee.children: + # children are also extension element instances + assert child.namespace == 'urn:oasis:names:tc:SAML:2.0:assertion' + assert child.tag == "AttributeValue" + +def test_ee_7(): + ee = saml2.extension_element_from_string( + """ + + + + http://federationX.org + + + + https://federationX.org/?ID=a87s76a5765da76576a57as + + +""") + + print ee.__dict__ + assert len(ee.children) == 2 + for child in ee.children: + assert child.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml" + assert _eq(["AssertingEntity","RetrievalEndpoint"], + [c.tag for c in ee.children]) + aes = [c for c in ee.children if c.tag == "AssertingEntity"] + assert len(aes) == 1 + assert len(aes[0].children) == 1 + assert _eq(aes[0].attributes.keys(),[]) + nid = aes[0].children[0] + assert nid.tag == "NameID" + assert nid.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml" + assert len(nid.children) == 0 + assert _eq(nid.attributes.keys(),["Format"]) + assert nid.text.strip() == "http://federationX.org" + + +def test_extension_element_loadd(): + ava = {'attributes': {}, + 'tag': 'ExternalEntityAttributeAuthority', + 'namespace': 'urn:oasis:names:tc:SAML:metadata:dynamicsaml', + 'children': [{ + "tag": "AssertingEntity", + "namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml", + "children": [{ + "tag":"NameID", + "namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml", + "text": "http://federationX.org", + "attributes":{ + "Format":"urn:oasis:names:tc:SAML:2.0:nameid-format:entity" + }, + }] + }, { + "tag":"RetrievalEndpoint", + "namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml", + "text":"https://federationX.org/?ID=a87s76a5765da76576a57as", + }], + } + + ee = saml2.ExtensionElement(ava["tag"]).loadd(ava) + print ee.__dict__ + assert len(ee.children) == 2 + for child in ee.children: + assert child.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml" + assert _eq(["AssertingEntity","RetrievalEndpoint"], + [c.tag for c in ee.children]) + aes = [c for c in ee.children if c.tag == "AssertingEntity"] + assert len(aes) == 1 + assert len(aes[0].children) == 1 + assert _eq(aes[0].attributes.keys(),[]) + nid = aes[0].children[0] + assert nid.tag == "NameID" + assert nid.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml" + assert len(nid.children) == 0 + assert _eq(nid.attributes.keys(),["Format"]) + assert nid.text.strip() == "http://federationX.org" + +def test_extensions_loadd(): + ava = {"extension_elements":[{'attributes': {}, + 'tag': 'ExternalEntityAttributeAuthority', + 'namespace': 'urn:oasis:names:tc:SAML:metadata:dynamicsaml', + 'children': [{ + "tag": "AssertingEntity", + "namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml", + "children": [{ + "tag":"NameID", + "namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml", + "text": "http://federationX.org", + "attributes":{ + "Format":"urn:oasis:names:tc:SAML:2.0:nameid-format:entity" + }, + }] + }, { + "tag":"RetrievalEndpoint", + "namespace": "urn:oasis:names:tc:SAML:metadata:dynamicsaml", + "text":"https://federationX.org/?ID=a87s76a5765da76576a57as", + }], + }], + "extension_attributes": { + "foo":"bar", + } + } + + extension = saml2.SamlBase() + extension.loadd(ava) + + print extension.__dict__ + assert len(extension.extension_elements) == 1 + ee = extension.extension_elements[0] + assert len(ee.children) == 2 + for child in ee.children: + assert child.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml" + assert _eq(["AssertingEntity","RetrievalEndpoint"], + [c.tag for c in ee.children]) + aes = [c for c in ee.children if c.tag == "AssertingEntity"] + assert len(aes) == 1 + assert len(aes[0].children) == 1 + assert _eq(aes[0].attributes.keys(),[]) + nid = aes[0].children[0] + assert nid.tag == "NameID" + assert nid.namespace == "urn:oasis:names:tc:SAML:metadata:dynamicsaml" + assert len(nid.children) == 0 + assert _eq(nid.attributes.keys(),["Format"]) + assert nid.text.strip() == "http://federationX.org" + + assert extension.extension_attributes.keys() == ["foo"] + assert extension.extension_attributes["foo"] == "bar" diff --git a/tests/test_04_samlp.py b/tests/test_04_samlp.py new file mode 100644 index 0000000..cada372 --- /dev/null +++ b/tests/test_04_samlp.py @@ -0,0 +1,538 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2009 Umeå University. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for saml2.samlp""" + +__author__ = 'roland.hedberg@adm.umu.se (Roland Hedberg)' + +import unittest +try: + from xml.etree import ElementTree +except ImportError: + from elementtree import ElementTree +import saml2 + +import saml2_data, ds_data, samlp_data + +from saml2 import saml +from saml2 import samlp +import xmldsig as ds + + +class TestRequestAbstractType: + + def setup_class(self): + self.ar = samlp.RequestAbstractType() + + def testAccessors(self): + """Test for RequestAbstractType accessors""" + self.ar.id = "request id" + self.ar.version = saml2.VERSION + self.ar.issue_instant = "2007-09-14T01:05:02Z" + self.ar.destination = "http://www.example.com/Destination" + self.ar.consent = saml.CONSENT_UNSPECIFIED + self.ar.issuer = saml.Issuer() + self.ar.signature = ds.Signature() + self.ar.extensions = samlp.Extensions() + + new_ar = samlp.request_abstract_type_from_string(self.ar.to_string()) + assert new_ar.id == "request id" + assert new_ar.version == saml2.VERSION + assert new_ar.issue_instant == "2007-09-14T01:05:02Z" + assert new_ar.destination == "http://www.example.com/Destination" + assert new_ar.consent == saml.CONSENT_UNSPECIFIED + assert isinstance(new_ar.issuer, saml.Issuer) + assert isinstance(new_ar.signature, ds.Signature) + assert isinstance(new_ar.extensions, samlp.Extensions) + + def testUsingTestData(self): + """Test for request_abstract_type_from_string() using test data""" + # TODO: + pass + +class TestStatusDetail: + + def setup_class(self): + self.status_detail = samlp.StatusDetail() + + def testAccessors(self): + """Test for StatusDetail accessors""" + # TODO: + pass + + +class TestStatusMessage: + + def setup_class(self): + self.status_message = samlp.StatusMessage() + + def testAccessors(self): + """Test for StatusMessage accessors""" + # TODO: + pass + + +class TestStatusCode: + + def setup_class(self): + self.status_code = samlp.StatusCode() + + def testAccessors(self): + """Test for StatusCode accessors""" + self.status_code.value = samlp.STATUS_RESPONDER + self.status_code.status_code = samlp.StatusCode( + value=samlp.STATUS_REQUEST_DENIED) + print self.status_code.__dict__ + new_status_code = samlp.status_code_from_string(self.status_code.to_string()) + assert new_status_code.value == samlp.STATUS_RESPONDER + assert new_status_code.status_code.value == \ + samlp.STATUS_REQUEST_DENIED + + def testUsingTestData(self): + """Test for status_code_from_string() using test data""" + new_status_code = samlp.status_code_from_string( + samlp_data.TEST_STATUS_CODE) + assert new_status_code.value == samlp.STATUS_RESPONDER + assert new_status_code.status_code.value == \ + samlp.STATUS_REQUEST_DENIED + + +class TestStatus: + + def setup_class(self): + self.status = samlp.Status() + + def testAccessors(self): + """Test for Status accessors""" + self.status.status_code = samlp.StatusCode() + self.status.status_message = samlp.StatusMessage() + self.status.status_detail = samlp.StatusDetail() + new_status = samlp.status_from_string(self.status.to_string()) + assert isinstance(new_status.status_code, samlp.StatusCode) + assert isinstance(new_status.status_message, samlp.StatusMessage) + assert isinstance(new_status.status_detail, samlp.StatusDetail) + + def testUsingTestData(self): + """Test for status_from_string using test data""" + new_status = samlp.status_from_string(samlp_data.TEST_STATUS) + assert isinstance(new_status.status_code, samlp.StatusCode) + assert isinstance(new_status.status_code.status_code, + samlp.StatusCode) + assert isinstance(new_status.status_message, samlp.StatusMessage) + assert isinstance(new_status.status_detail, samlp.StatusDetail) + +class TestStatusResponseType: + + def setup_class(self): + self.sr = samlp.StatusResponseType() + + def testAccessors(self): + """Test for StatusResponseType accessors""" + self.sr.id = "response id" + self.sr.in_response_to = "request id" + self.sr.version = saml2.VERSION + self.sr.issue_instant = "2007-09-14T01:05:02Z" + self.sr.destination = "http://www.example.com/Destination" + self.sr.consent = saml.CONSENT_UNSPECIFIED + self.sr.issuer = saml.Issuer() + self.sr.signature = ds.Signature() + self.sr.extensions = samlp.Extensions() + self.sr.status = samlp.Status() + + new_sr = samlp.status_response_type_from_string(self.sr.to_string()) + assert new_sr.id == "response id" + assert new_sr.in_response_to == "request id" + assert new_sr.version == saml2.VERSION + assert new_sr.issue_instant == "2007-09-14T01:05:02Z" + assert new_sr.destination == "http://www.example.com/Destination" + assert new_sr.consent == saml.CONSENT_UNSPECIFIED + assert isinstance(new_sr.issuer, saml.Issuer) + assert isinstance(new_sr.signature, ds.Signature) + assert isinstance(new_sr.extensions, samlp.Extensions) + assert isinstance(new_sr.status, samlp.Status) + + def testUsingTestData(self): + """Test for status_response_from_string() using test data""" + # TODO: + pass + + +class TestResponse: + + def setup_class(self): + self.response = samlp.Response() + + def testAccessors(self): + """Test for Response accessors""" + self.response.id = "response id" + self.response.in_response_to = "request id" + self.response.version = saml2.VERSION + self.response.issue_instant = "2007-09-14T01:05:02Z" + self.response.destination = "http://www.example.com/Destination" + self.response.consent = saml.CONSENT_UNSPECIFIED + self.response.issuer = saml.Issuer() + self.response.signature = ds.Signature() + self.response.extensions = samlp.Extensions() + self.response.status = samlp.Status() + self.response.assertion.append(saml.Assertion()) + self.response.encrypted_assertion.append(saml.EncryptedAssertion()) + + new_response = samlp.response_from_string(self.response.to_string()) + assert new_response.id == "response id" + assert new_response.in_response_to == "request id" + assert new_response.version == saml2.VERSION + assert new_response.issue_instant == "2007-09-14T01:05:02Z" + assert new_response.destination == "http://www.example.com/Destination" + assert new_response.consent == saml.CONSENT_UNSPECIFIED + assert isinstance(new_response.issuer, saml.Issuer) + assert isinstance(new_response.signature, ds.Signature) + assert isinstance(new_response.extensions, samlp.Extensions) + assert isinstance(new_response.status, samlp.Status) + + assert isinstance(new_response.assertion[0], saml.Assertion) + assert isinstance(new_response.encrypted_assertion[0], + saml.EncryptedAssertion) + + def testUsingTestData(self): + """Test for response_from_string() using test data""" + # TODO: + pass + +class TestNameIDPolicy: + + def setup_class(self): + self.name_id_policy = samlp.NameIDPolicy() + + def testAccessors(self): + """Test for NameIDPolicy accessors""" + self.name_id_policy.format = saml.NAMEID_FORMAT_EMAILADDRESS + self.name_id_policy.sp_name_qualifier = saml.NAMEID_FORMAT_PERSISTENT + self.name_id_policy.allow_create = 'false' + + new_name_id_policy = samlp.name_id_policy_from_string( + self.name_id_policy.to_string()) + + assert new_name_id_policy.format == saml.NAMEID_FORMAT_EMAILADDRESS + assert new_name_id_policy.sp_name_qualifier == \ + saml.NAMEID_FORMAT_PERSISTENT + assert new_name_id_policy.allow_create == 'false' + + def testUsingTestData(self): + """Test for name_id_policy_from_string() using test data""" + new_name_id_policy = samlp.name_id_policy_from_string( + samlp_data.TEST_NAME_ID_POLICY) + + assert new_name_id_policy.format == saml.NAMEID_FORMAT_EMAILADDRESS + assert new_name_id_policy.sp_name_qualifier == \ + saml.NAMEID_FORMAT_PERSISTENT + assert new_name_id_policy.allow_create == 'false' + + +class TestIDPEntry: + + def setup_class(self): + self.idp_entry = samlp.IDPEntry() + + def testAccessors(self): + """Test for IDPEntry accessors""" + self.idp_entry.provider_id = "http://www.example.com/provider" + self.idp_entry.name = "the provider" + self.idp_entry.loc = "http://www.example.com/Loc" + + new_idp_entry = samlp.idp_entry_from_string(self.idp_entry.to_string()) + assert new_idp_entry.provider_id == "http://www.example.com/provider" + assert new_idp_entry.name == "the provider" + assert new_idp_entry.loc == "http://www.example.com/Loc" + + def testUsingTestData(self): + """Test for idp_entry_from_string() using test data""" + new_idp_entry = samlp.idp_entry_from_string(samlp_data.TEST_IDP_ENTRY) + assert new_idp_entry.provider_id == "http://www.example.com/provider" + assert new_idp_entry.name == "the provider" + assert new_idp_entry.loc == "http://www.example.com/Loc" + + +class TestIDPList: + + def setup_class(self): + self.idp_list = samlp.IDPList() + + def testAccessors(self): + """Test for IDPList accessors""" + self.idp_list.idp_entry.append(samlp.idp_entry_from_string( + samlp_data.TEST_IDP_ENTRY)) + self.idp_list.get_complete = samlp.GetComplete( + text="http://www.example.com/GetComplete") + new_idp_list = samlp.idp_list_from_string(self.idp_list.to_string()) + assert isinstance(new_idp_list.idp_entry[0], samlp.IDPEntry) + assert new_idp_list.get_complete.text.strip() == \ + "http://www.example.com/GetComplete" + + def testUsingTestData(self): + """Test for idp_list_from_string() using test data""" + new_idp_list = samlp.idp_list_from_string(samlp_data.TEST_IDP_LIST) + assert isinstance(new_idp_list.idp_entry[0], samlp.IDPEntry) + assert new_idp_list.get_complete.text.strip() == \ + "http://www.example.com/GetComplete" + + +class TestScoping: + + def setup_class(self): + self.scoping = samlp.Scoping() + + def testAccessors(self): + """Test for Scoping accessors""" + + self.scoping.proxy_count = "1" + self.scoping.idp_list = samlp.IDPList() + self.scoping.requester_id.append(samlp.RequesterID()) + + new_scoping = samlp.scoping_from_string(self.scoping.to_string()) + + assert new_scoping.proxy_count == "1" + assert isinstance(new_scoping.idp_list, samlp.IDPList) + assert isinstance(new_scoping.requester_id[0], samlp.RequesterID) + + def testUsingTestData(self): + """Test for scoping_from_string() using test data""" + new_scoping = samlp.scoping_from_string(samlp_data.TEST_SCOPING) + + assert new_scoping.proxy_count == "1" + assert isinstance(new_scoping.idp_list, samlp.IDPList) + assert isinstance(new_scoping.requester_id[0], samlp.RequesterID) + + +class TestRequestedAuthnContext: + + def setup_class(self): + self.context = samlp.RequestedAuthnContext() + + def testAccessors(self): + """Test for RequestedAuthnContext accessors""" + + self.context.authn_context_class_ref.append(saml.AuthnContextClassRef()) + self.context.authn_context_decl_ref.append(saml.AuthnContextDeclRef()) + self.context.comparison = "exact" + + new_context = samlp.requested_authn_context_from_string( + self.context.to_string()) + + assert isinstance(new_context.authn_context_class_ref[0], + saml.AuthnContextClassRef) + assert isinstance(new_context.authn_context_decl_ref[0], + saml.AuthnContextDeclRef) + assert new_context.comparison == "exact" + + def testUsingTestData(self): + """Test for requested_authn_context_from_string() using test data""" + new_context = samlp.requested_authn_context_from_string( + samlp_data.TEST_REQUESTED_AUTHN_CONTEXT) + + assert isinstance(new_context.authn_context_class_ref[0], + saml.AuthnContextClassRef) + assert isinstance(new_context.authn_context_decl_ref[0], + saml.AuthnContextDeclRef) + assert new_context.comparison == "exact" + + +class TestAuthnRequest: + + def setup_class(self): + self.ar = samlp.AuthnRequest() + + def testAccessors(self): + """Test for AuthnRequest accessors""" + self.ar.id = "request id" + self.ar.version = saml2.VERSION + self.ar.issue_instant = "2007-09-14T01:05:02Z" + self.ar.destination = "http://www.example.com/Destination" + self.ar.consent = saml.CONSENT_UNSPECIFIED + self.ar.issuer = saml.Issuer() + self.ar.signature = ds.Signature() + self.ar.extensions = samlp.Extensions() + + self.ar.subject = saml.Subject() + self.ar.name_id_policy = samlp.NameIDPolicy() + self.ar.conditions = saml.Conditions() + self.ar.requested_authn_context = samlp.RequestedAuthnContext() + self.ar.scoping = samlp.Scoping() + self.ar.force_authn = 'true' + self.ar.is_passive = 'true' + self.ar.assertion_consumer_service_index = "1" + self.ar.assertion_consumer_service_url = "http://www.example.com/acs" + self.ar.protocol_binding = saml2.BINDING_HTTP_POST + self.ar.attribute_consuming_service_index = "2" + self.ar.provider_name = "provider name" + + new_ar = samlp.authn_request_from_string(self.ar.to_string()) + assert new_ar.id == "request id" + assert new_ar.version == saml2.VERSION + assert new_ar.issue_instant == "2007-09-14T01:05:02Z" + assert new_ar.destination == "http://www.example.com/Destination" + assert new_ar.consent == saml.CONSENT_UNSPECIFIED + assert isinstance(new_ar.issuer, saml.Issuer) + assert isinstance(new_ar.signature, ds.Signature) + assert isinstance(new_ar.extensions, samlp.Extensions) + + assert isinstance(new_ar.subject, saml.Subject) + assert isinstance(new_ar.name_id_policy, samlp.NameIDPolicy) + assert isinstance(new_ar.conditions, saml.Conditions) + assert isinstance(new_ar.requested_authn_context, + samlp.RequestedAuthnContext) + assert isinstance(new_ar.scoping, samlp.Scoping) + assert new_ar.force_authn == 'true' + assert new_ar.is_passive == 'true' + assert new_ar.assertion_consumer_service_index == '1' + assert new_ar.assertion_consumer_service_url == \ + 'http://www.example.com/acs' + assert new_ar.protocol_binding == saml2.BINDING_HTTP_POST + assert new_ar.attribute_consuming_service_index == '2' + assert new_ar.provider_name == "provider name" + + def testUsingTestData(self): + """Test for authn_request_from_string() using test data""" + new_ar = samlp.authn_request_from_string(samlp_data.TEST_AUTHN_REQUEST) + assert new_ar.id == "request id" + assert new_ar.version == saml2.VERSION + assert new_ar.issue_instant == "2007-09-14T01:05:02Z" + assert new_ar.destination == "http://www.example.com/Destination" + assert new_ar.consent == saml.CONSENT_UNSPECIFIED + assert isinstance(new_ar.issuer, saml.Issuer) + assert isinstance(new_ar.signature, ds.Signature) + assert isinstance(new_ar.extensions, samlp.Extensions) + + assert isinstance(new_ar.subject, saml.Subject) + assert isinstance(new_ar.name_id_policy, samlp.NameIDPolicy) + assert isinstance(new_ar.conditions, saml.Conditions) + assert isinstance(new_ar.requested_authn_context, + samlp.RequestedAuthnContext) + assert isinstance(new_ar.scoping, samlp.Scoping) + assert new_ar.force_authn == 'true' + assert new_ar.is_passive == 'true' + assert new_ar.assertion_consumer_service_index == '1' + assert new_ar.assertion_consumer_service_url == \ + 'http://www.example.com/acs' + assert new_ar.protocol_binding == saml2.BINDING_HTTP_POST + assert new_ar.attribute_consuming_service_index == '2' + assert new_ar.provider_name == "provider name" + + +class TestLogoutRequest: + + def setup_class(self): + self.lr = samlp.LogoutRequest() + + def testAccessors(self): + """Test for LogoutRequest accessors""" + self.lr.id = "request id" + self.lr.version = saml2.VERSION + self.lr.issue_instant = "2007-09-14T01:05:02Z" + self.lr.destination = "http://www.example.com/Destination" + self.lr.consent = saml.CONSENT_UNSPECIFIED + self.lr.issuer = saml.Issuer() + self.lr.signature = ds.Signature() + self.lr.extensions = samlp.Extensions() + + self.lr.not_on_or_after = "2007-10-14T01:05:02Z" + self.lr.reason = "http://www.example.com/Reason" + self.lr.base_id = saml.BaseID() + self.lr.name_id = saml.NameID() + self.lr.encrypted_id = saml.EncryptedID() + self.lr.session_index = samlp.SessionIndex() + + new_lr = samlp.logout_request_from_string(self.lr.to_string()) + assert new_lr.id == "request id" + assert new_lr.version == saml2.VERSION + assert new_lr.issue_instant == "2007-09-14T01:05:02Z" + assert new_lr.destination == "http://www.example.com/Destination" + assert new_lr.consent == saml.CONSENT_UNSPECIFIED + assert isinstance(new_lr.issuer, saml.Issuer) + assert isinstance(new_lr.signature, ds.Signature) + assert isinstance(new_lr.extensions, samlp.Extensions) + assert new_lr.not_on_or_after == "2007-10-14T01:05:02Z" + assert new_lr.reason == "http://www.example.com/Reason" + assert isinstance(new_lr.base_id, saml.BaseID) + assert isinstance(new_lr.name_id, saml.NameID) + assert isinstance(new_lr.encrypted_id, saml.EncryptedID) + assert isinstance(new_lr.session_index[0], samlp.SessionIndex) + + def testUsingTestData(self): + """Test for logout_request_from_string() using test data""" + new_lr = samlp.logout_request_from_string(samlp_data.TEST_LOGOUT_REQUEST) + assert new_lr.id == "request id" + assert new_lr.version == saml2.VERSION + assert new_lr.issue_instant == "2007-09-14T01:05:02Z" + assert new_lr.destination == "http://www.example.com/Destination" + assert new_lr.consent == saml.CONSENT_UNSPECIFIED + assert isinstance(new_lr.issuer, saml.Issuer) + assert isinstance(new_lr.signature, ds.Signature) + assert isinstance(new_lr.extensions, samlp.Extensions) + assert new_lr.not_on_or_after == "2007-10-14T01:05:02Z" + assert new_lr.reason == "http://www.example.com/Reason" + assert isinstance(new_lr.base_id, saml.BaseID) + assert isinstance(new_lr.name_id, saml.NameID) + assert isinstance(new_lr.encrypted_id, saml.EncryptedID) + assert isinstance(new_lr.session_index[0], samlp.SessionIndex) + assert new_lr.session_index[0].text.strip() == "session index" + + +class TestLogoutResponse: + + def setup_class(self): + self.lr = samlp.LogoutResponse() + + def testAccessors(self): + """Test for LogoutResponse accessors""" + self.lr.id = "response id" + self.lr.in_response_to = "request id" + self.lr.version = saml2.VERSION + self.lr.issue_instant = "2007-09-14T01:05:02Z" + self.lr.destination = "http://www.example.com/Destination" + self.lr.consent = saml.CONSENT_UNSPECIFIED + self.lr.issuer = saml.Issuer() + self.lr.signature = ds.Signature() + self.lr.extensions = samlp.Extensions() + self.lr.status = samlp.Status() + + new_lr = samlp.logout_response_from_string(self.lr.to_string()) + assert new_lr.id == "response id" + assert new_lr.in_response_to == "request id" + assert new_lr.version == saml2.VERSION + assert new_lr.issue_instant == "2007-09-14T01:05:02Z" + assert new_lr.destination == "http://www.example.com/Destination" + assert new_lr.consent == saml.CONSENT_UNSPECIFIED + assert isinstance(new_lr.issuer, saml.Issuer) + assert isinstance(new_lr.signature, ds.Signature) + assert isinstance(new_lr.extensions, samlp.Extensions) + assert isinstance(new_lr.status, samlp.Status) + + def testUsingTestData(self): + """Test for logout_response_from_string() using test data""" + new_lr = samlp.logout_response_from_string( + samlp_data.TEST_LOGOUT_RESPONSE) + assert new_lr.id == "response id" + assert new_lr.in_response_to == "request id" + assert new_lr.version == saml2.VERSION + assert new_lr.issue_instant == "2007-09-14T01:05:02Z" + assert new_lr.destination == "http://www.example.com/Destination" + assert new_lr.consent == saml.CONSENT_UNSPECIFIED + assert isinstance(new_lr.issuer, saml.Issuer) + assert isinstance(new_lr.signature, ds.Signature) + assert isinstance(new_lr.extensions, samlp.Extensions) + assert isinstance(new_lr.status, samlp.Status) + diff --git a/tests/test_05_md.py b/tests/test_05_md.py new file mode 100644 index 0000000..f36ebcb --- /dev/null +++ b/tests/test_05_md.py @@ -0,0 +1,1143 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2009 Umeå University. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for saml2.md""" + +__author__ = 'roland.hedberg@umu.se (Roland Hedberg)' + +import unittest +try: + from xml.etree import ElementTree +except ImportError: + from elementtree import ElementTree + +import saml2 +import xmldsig as ds + +from saml2 import saml +from saml2 import samlp +from saml2 import md +from saml2 import idpdisc + +from saml2 import element_to_extension_element, extension_element_to_element +import md_data, ds_data + +class TestEndpointType: + + def setup_class(self): + self.endpoint = md.EndpointType() + + def testAccessors(self): + """Test for EndpointType accessors""" + self.endpoint.binding = saml2.BINDING_HTTP_POST + self.endpoint.location = "http://www.example.com/endpoint" + self.endpoint.response_location = "http://www.example.com/response" + print self.endpoint.__class__.c_attributes.items() + new_endpoint = md.endpoint_type_from_string(self.endpoint.to_string()) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + + def testUsingTestData(self): + """Test for endpoint_type_from_string() using test data.""" + new_endpoint = md.endpoint_type_from_string(md_data.TEST_ENDPOINT) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + + +class TestIndexedEndpointType: + + def setup_class(self): + self.i_e = md.IndexedEndpointType() + + def testAccessors(self): + """Test for IndexedEndpointType accessors""" + self.i_e.binding = saml2.BINDING_HTTP_POST + self.i_e.location = "http://www.example.com/endpoint" + self.i_e.response_location = "http://www.example.com/response" + self.i_e.index = "1" + self.i_e.is_default = "false" + new_i_e = md.indexed_endpoint_type_from_string(self.i_e.to_string()) + assert new_i_e.binding == saml2.BINDING_HTTP_POST + assert new_i_e.location == "http://www.example.com/endpoint" + assert new_i_e.response_location == "http://www.example.com/response" + assert new_i_e.index == "1" + assert new_i_e.is_default == "false" + + def testUsingTestData(self): + """Test for indexed_endpoint_type_from_string() using test data.""" + new_i_e = md.indexed_endpoint_type_from_string(md_data.TEST_INDEXED_ENDPOINT) + assert new_i_e.binding == saml2.BINDING_HTTP_POST + assert new_i_e.location == "http://www.example.com/endpoint" + assert new_i_e.response_location == "http://www.example.com/response" + assert new_i_e.index == "1" + assert new_i_e.is_default == "false" + + +class TestExtensions: + + def setup_class(self): + self.extensions = md.Extensions() + + def testAccessors(self): + """Test for Extensions accessors""" + self.extensions.extension_elements.append( + saml2.extension_element_from_string( + """ + fuga + """)) + new_extensions = md.extensions_from_string(self.extensions.to_string()) + assert new_extensions.extension_elements[0].tag == "hoge" + assert new_extensions.extension_elements[0].text.strip() == "fuga" + + +class TestOrganizationName: + + def setup_class(self): + self.organization_name = md.OrganizationName() + + def testAccessors(self): + """Test for OrganizationName accessors""" + self.organization_name.lang = "en" + self.organization_name.text = "SIOS Technology, Inc." + new_organization_name = md.organization_name_from_string( + self.organization_name.to_string()) + assert new_organization_name.lang == "en" + assert new_organization_name.text.strip() == "SIOS Technology, Inc." + + def testUsingTestData(self): + """Test for organization_name_from_string() using test data.""" + new_organization_name = md.organization_name_from_string( + md_data.TEST_ORGANIZATION_NAME) + print new_organization_name.keyswv() + assert new_organization_name.lang == "se" + assert new_organization_name.text.strip() == "Catalogix" + + +class TestOrganizationDisplayName: + + def setup_class(self): + self.od_name = md.OrganizationDisplayName() + + def testAccessors(self): + """Test for OrganizationDisplayName accessors""" + self.od_name.lang = "en" + self.od_name.text = "SIOS" + new_od_name = md.organization_display_name_from_string( + self.od_name.to_string()) + assert new_od_name.lang == "en" + assert new_od_name.text.strip() == "SIOS" + + def testUsingTestData(self): + """Test for organization_display_name_from_string() using test data.""" + new_od_name = md.organization_display_name_from_string( + md_data.TEST_ORGANIZATION_DISPLAY_NAME) + assert new_od_name.lang == "se" + assert new_od_name.text.strip() == "Catalogix" + + +class TestOrganizationURL: + + def setup_class(self): + self.organization_url = md.OrganizationURL() + + def testAccessors(self): + """Test for OrganizationURL accessors""" + self.organization_url.lang = "ja" + self.organization_url.text = "http://www.example.com/" + print self.organization_url.to_string() + new_organization_url = md.organization_url_from_string( + self.organization_url.to_string()) + assert new_organization_url.lang == "ja" + assert new_organization_url.text.strip() == "http://www.example.com/" + + def testUsingTestData(self): + """Test for organization_url_from_string() using test data.""" + new_organization_url = md.organization_url_from_string( + md_data.TEST_ORGANIZATION_URL) + assert new_organization_url.lang == "no" + assert new_organization_url.text.strip() == "http://www.example.com/" + + +class TestOrganization: + + def setup_class(self): + self.organization = md.Organization() + + def testAccessors(self): + """Test for Organization accessors""" + self.organization.extensions = md.Extensions() + self.organization.organization_name.append( + md.organization_name_from_string(md_data.TEST_ORGANIZATION_NAME)) + self.organization.organization_display_name.append( + md.organization_display_name_from_string( + md_data.TEST_ORGANIZATION_DISPLAY_NAME)) + self.organization.organization_url.append( + md.organization_url_from_string(md_data.TEST_ORGANIZATION_URL)) + new_organization = md.organization_from_string(self.organization.to_string()) + assert isinstance(new_organization.extensions, md.Extensions) + assert isinstance(new_organization.organization_name[0], + md.OrganizationName) + assert isinstance(new_organization.organization_display_name[0], + md.OrganizationDisplayName) + assert isinstance(new_organization.organization_url[0], + md.OrganizationURL) + assert new_organization.organization_name[0].text.strip() == "Catalogix" + assert new_organization.organization_name[0].lang == "se" + assert new_organization.organization_display_name[0].text.strip() == "Catalogix" + assert new_organization.organization_display_name[0].lang == "se" + assert new_organization.organization_url[0].text.strip() == "http://www.example.com/" + assert new_organization.organization_url[0].lang == "no" + + + def testUsingTestData(self): + """Test for organization_from_string() using test data.""" + new_organization = md.organization_from_string( + md_data.TEST_ORGANIZATION) + assert isinstance(new_organization.extensions, md.Extensions) + assert isinstance(new_organization.organization_name[0], + md.OrganizationName) + assert isinstance(new_organization.organization_display_name[0], + md.OrganizationDisplayName) + assert isinstance(new_organization.organization_url[0], + md.OrganizationURL) + assert new_organization.organization_name[0].text.strip() == "Catalogix AB" + assert new_organization.organization_name[0].lang == "se" + assert new_organization.organization_display_name[0].text.strip() == "Catalogix AS" + assert new_organization.organization_display_name[0].lang == "no" + assert new_organization.organization_url[0].text.strip() == "http://www.example.com/" + assert new_organization.organization_url[0].lang == "en" + + +class TestContactPerson: + + def setup_class(self): + self.contact_person = md.ContactPerson() + + def testAccessors(self): + """Test for ContactPerson accessors""" + self.contact_person.contact_type = "technical" + self.contact_person.extensions = md.Extensions() + self.contact_person.company = md.Company(text="SIOS Technology, Inc.") + self.contact_person.given_name = md.GivenName(text="Takashi") + self.contact_person.sur_name = md.SurName(text="Matsuo") + self.contact_person.email_address.append( + md.EmailAddress(text="tmatsuo@example.com")) + self.contact_person.email_address.append( + md.EmailAddress(text="tmatsuo@shehas.net")) + self.contact_person.telephone_number.append( + md.TelephoneNumber(text="00-0000-0000")) + new_contact_person = md.contact_person_from_string( + self.contact_person.to_string()) + assert new_contact_person.contact_type == "technical" + assert isinstance(new_contact_person.extensions, md.Extensions) + assert new_contact_person.company.text.strip() == "SIOS Technology, Inc." + assert new_contact_person.given_name.text.strip() == "Takashi" + assert new_contact_person.sur_name.text.strip() == "Matsuo" + assert new_contact_person.email_address[0].text.strip() == "tmatsuo@example.com" + assert new_contact_person.email_address[1].text.strip() == "tmatsuo@shehas.net" + assert new_contact_person.telephone_number[0].text.strip() == "00-0000-0000" + + def testUsingTestData(self): + """Test for contact_person_from_string() using test data.""" + new_contact_person = md.contact_person_from_string( + md_data.TEST_CONTACT_PERSON) + assert new_contact_person.contact_type == "technical" + assert isinstance(new_contact_person.extensions, md.Extensions) + assert new_contact_person.company.text.strip() == "SIOS Technology, Inc." + assert new_contact_person.given_name.text.strip() == "Takashi" + assert new_contact_person.sur_name.text.strip() == "Matsuo" + assert new_contact_person.email_address[0].text.strip() == "tmatsuo@example.com" + assert new_contact_person.email_address[1].text.strip() == "tmatsuo@shehas.net" + assert new_contact_person.telephone_number[0].text.strip() == "00-0000-0000" + +class TestAdditionalMetadataLocation: + + def setup_class(self): + self.additional_metadata_location = md.AdditionalMetadataLocation() + + def testAccessors(self): + """Test for AdditionalMetadataLocation accessors""" + self.additional_metadata_location.namespace = ( + "http://www.example.com/namespace") + self.additional_metadata_location.text = ( + "http://www.example.com/AdditionalMetadataLocation") + new_additional_metadata_location = md.additional_metadata_location_from_string( + self.additional_metadata_location.to_string()) + assert new_additional_metadata_location.namespace == "http://www.example.com/namespace" + assert new_additional_metadata_location.text.strip() == "http://www.example.com/AdditionalMetadataLocation" + + def testUsingTestData(self): + """Test for additional_metadata_location_from_string() using test data.""" + new_additional_metadata_location = md.additional_metadata_location_from_string( + md_data.TEST_ADDITIONAL_METADATA_LOCATION) + assert new_additional_metadata_location.namespace == "http://www.example.com/namespace" + assert new_additional_metadata_location.text.strip() == "http://www.example.com/AdditionalMetadataLocation" + +# class TestKeySize: +# +# def setup_class(self): +# self.key_size = md.KeySize() +# +# def testAccessors(self): +# """Test for KeySize accessors""" +# self.key_size.text = "128" +# new_key_size = md.key_size_from_string(self.key_size.to_string()) +# assert new_key_size.text.strip() == "128" +# +# def testUsingTestData(self): +# """Test for key_size_from_string() using test data.""" +# new_key_size = md.key_size_from_string(md_data.TEST_KEY_SIZE) +# assert new_key_size.text.strip() == "128" + + +# class TestOAEPparams: +# +# def setup_class(self): +# self.oaep_params = md.OAEPparams() +# +# def testAccessors(self): +# """Test for OAEPparams accessors""" +# self.oaep_params.text = "9lWu3Q==" +# new_oaep_params = md.oae_pparams_from_string(self.oaep_params.to_string()) +# assert new_oaep_params.text.strip() == "9lWu3Q==" +# +# def testUsingTestData(self): +# """Test for oae_pparams_from_string() using test data.""" +# new_oaep_params = md.oae_pparams_from_string(md_data.TEST_OAEP_PARAMS) +# assert new_oaep_params.text.strip() == "9lWu3Q==" + + +class TestEncryptionMethod: + + def setup_class(self): + self.encryption_method = md.EncryptionMethod() + + def testAccessors(self): + """Test for EncryptionMethod accessors""" + self.encryption_method.algorithm = ( + "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p") + new_encryption_method = md.encryption_method_from_string( + self.encryption_method.to_string()) + assert new_encryption_method.algorithm == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" + + def testUsingTestData(self): + """Test for encryption_method_from_string() using test data.""" + new_encryption_method = md.encryption_method_from_string( + md_data.TEST_ENCRYPTION_METHOD) + assert new_encryption_method.algorithm == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" + assert new_encryption_method.oae_pparams.text.strip() == "9lWu3Q==" + + +class TestKeyDescriptor: + + def setup_class(self): + self.key_descriptor = md.KeyDescriptor() + + def testAccessors(self): + """Test for KeyDescriptor accessors""" + + self.key_descriptor.use = "signing" + self.key_descriptor.key_info = ds.key_info_from_string( + ds_data.TEST_KEY_INFO) + self.key_descriptor.encryption_method.append(md.encryption_method_from_string( + md_data.TEST_ENCRYPTION_METHOD)) + new_key_descriptor = md.key_descriptor_from_string( + self.key_descriptor.to_string()) + assert new_key_descriptor.use == "signing" + assert isinstance(new_key_descriptor.key_info, ds.KeyInfo) + assert isinstance(new_key_descriptor.encryption_method[0], + md.EncryptionMethod) + + def testUsingTestData(self): + """Test for key_descriptor_from_string() using test data.""" + new_key_descriptor = md.key_descriptor_from_string( + md_data.TEST_KEY_DESCRIPTOR) + assert new_key_descriptor.use == "signing" + assert isinstance(new_key_descriptor.key_info, ds.KeyInfo) + assert isinstance(new_key_descriptor.encryption_method[0], + md.EncryptionMethod) + + +class TestRoleDescriptor: + def setup_class(self): + self.role_descriptor = md.RoleDescriptor() + + def testAccessors(self): + """Test for RoleDescriptor accessors""" + self.role_descriptor.id = "ID" + self.role_descriptor.valid_until = "2008-09-14T01:05:02Z" + self.role_descriptor.cache_duration = "10:00:00:00" + self.role_descriptor.protocol_support_enumeration = samlp.NAMESPACE + self.role_descriptor.error_url = "http://www.example.com/errorURL" + self.role_descriptor.signature = ds.Signature() + self.role_descriptor.extensions = md.Extensions() + self.role_descriptor.key_descriptor.append(md.key_descriptor_from_string( + md_data.TEST_KEY_DESCRIPTOR)) + self.role_descriptor.organization = md.Organization() + self.role_descriptor.contact_person.append(md.ContactPerson()) + + new_role_descriptor = md.role_descriptor_from_string( + self.role_descriptor.to_string()) + assert new_role_descriptor.id == "ID" + assert new_role_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_role_descriptor.cache_duration == "10:00:00:00" + assert new_role_descriptor.protocol_support_enumeration == samlp.NAMESPACE + assert new_role_descriptor.error_url == "http://www.example.com/errorURL" + assert isinstance(new_role_descriptor.signature, ds.Signature) + assert isinstance(new_role_descriptor.extensions, md.Extensions) + assert isinstance(new_role_descriptor.key_descriptor[0], + md.KeyDescriptor) + assert isinstance(new_role_descriptor.organization, md.Organization) + assert isinstance(new_role_descriptor.contact_person[0], + md.ContactPerson) + + def testUsingTestData(self): + """Test for role_descriptor_from_string() using test data.""" + new_role_descriptor = md.role_descriptor_from_string( + md_data.TEST_ROLE_DESCRIPTOR) + assert new_role_descriptor.id == "ID" + assert new_role_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_role_descriptor.cache_duration == "10:00:00:00" + assert new_role_descriptor.protocol_support_enumeration == samlp.NAMESPACE + assert new_role_descriptor.error_url == "http://www.example.com/errorURL" + assert isinstance(new_role_descriptor.signature, ds.Signature) + assert isinstance(new_role_descriptor.extensions, md.Extensions) + assert isinstance(new_role_descriptor.key_descriptor[0], + md.KeyDescriptor) + assert isinstance(new_role_descriptor.organization, md.Organization) + assert isinstance(new_role_descriptor.contact_person[0], + md.ContactPerson) + +class TestSSODescriptor: + def setup_class(self): + self.sso_descriptor = md.SSODescriptorType() + + def testAccessors(self): + """Test for SSODescriptorType accessors""" + self.sso_descriptor.id = "ID" + self.sso_descriptor.valid_until = "2008-09-14T01:05:02Z" + self.sso_descriptor.cache_duration = "10:00:00:00" + self.sso_descriptor.protocol_support_enumeration = samlp.NAMESPACE + self.sso_descriptor.error_url = "http://www.example.com/errorURL" + self.sso_descriptor.signature = ds.Signature() + self.sso_descriptor.extensions = md.Extensions() + self.sso_descriptor.key_descriptor.append(md.key_descriptor_from_string( + md_data.TEST_KEY_DESCRIPTOR)) + self.sso_descriptor.organization = md.Organization() + self.sso_descriptor.contact_person.append(md.ContactPerson()) + self.sso_descriptor.artifact_resolution_service.append( + md.ArtifactResolutionService()) + self.sso_descriptor.single_logout_service.append( + md.SingleLogoutService()) + self.sso_descriptor.manage_name_id_service.append( + md.ManageNameIDService()) + self.sso_descriptor.name_id_format.append( + md.NameIDFormat()) + + new_sso_descriptor = md.sso_descriptor_type_from_string( + self.sso_descriptor.to_string()) + assert new_sso_descriptor.id == "ID" + assert new_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_sso_descriptor.cache_duration == "10:00:00:00" + assert new_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE + assert new_sso_descriptor.error_url == "http://www.example.com/errorURL" + assert isinstance(new_sso_descriptor.signature, ds.Signature) + assert isinstance(new_sso_descriptor.extensions, md.Extensions) + assert isinstance(new_sso_descriptor.key_descriptor[0], + md.KeyDescriptor) + assert isinstance(new_sso_descriptor.organization, md.Organization) + assert isinstance(new_sso_descriptor.contact_person[0], + md.ContactPerson) + assert isinstance(new_sso_descriptor.artifact_resolution_service[0], + md.ArtifactResolutionService) + assert isinstance(new_sso_descriptor.single_logout_service[0], + md.SingleLogoutService) + assert isinstance(new_sso_descriptor.manage_name_id_service[0], + md.ManageNameIDService) + assert isinstance(new_sso_descriptor.name_id_format[0], + md.NameIDFormat) + + +class TestArtifactResolutionService: + + def setup_class(self): + self.i_e = md.ArtifactResolutionService() + + def testAccessors(self): + """Test for ArtifactResolutionService accessors""" + self.i_e.binding = saml2.BINDING_HTTP_POST + self.i_e.location = "http://www.example.com/endpoint" + self.i_e.response_location = "http://www.example.com/response" + self.i_e.index = "1" + self.i_e.is_default = "false" + new_i_e = md.artifact_resolution_service_from_string(self.i_e.to_string()) + assert new_i_e.binding == saml2.BINDING_HTTP_POST + assert new_i_e.location == "http://www.example.com/endpoint" + assert new_i_e.response_location == "http://www.example.com/response" + assert new_i_e.index == "1" + assert new_i_e.is_default == "false" + + def testUsingTestData(self): + """Test for artifact_resolution_service_from_string() using test data.""" + new_i_e = md.artifact_resolution_service_from_string( + md_data.TEST_ARTIFACT_RESOLUTION_SERVICE) + assert new_i_e.binding == saml2.BINDING_HTTP_POST + assert new_i_e.location == "http://www.example.com/endpoint" + assert new_i_e.response_location == "http://www.example.com/response" + assert new_i_e.index == "1" + assert new_i_e.is_default == "false" + + +class TestSingleLogout: + + def setup_class(self): + self.endpoint = md.SingleLogoutService() + + def testAccessors(self): + """Test for SingleLogoutService accessors""" + self.endpoint.binding = saml2.BINDING_HTTP_POST + self.endpoint.location = "http://www.example.com/endpoint" + self.endpoint.response_location = "http://www.example.com/response" + new_endpoint = md.single_logout_service_from_string(self.endpoint.to_string()) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + + def testUsingTestData(self): + """Test for single_logout_service_from_string() using test data.""" + new_endpoint = md.single_logout_service_from_string( + md_data.TEST_SINGLE_LOGOUT_SERVICE) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + + +class TestManageNameIDService: + + def setup_class(self): + self.endpoint = md.ManageNameIDService() + + def testAccessors(self): + """Test for ManageNameIDService accessors""" + self.endpoint.binding = saml2.BINDING_HTTP_POST + self.endpoint.location = "http://www.example.com/endpoint" + self.endpoint.response_location = "http://www.example.com/response" + new_endpoint = md.manage_name_id_service_from_string(self.endpoint.to_string()) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + + def testUsingTestData(self): + """Test for manage_name_id_service_from_string() using test data.""" + new_endpoint = md.manage_name_id_service_from_string( + md_data.TEST_MANAGE_NAMEID_SERVICE) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + + +class TestNameIDFormat: + + def setup_class(self): + self.name_id_format = md.NameIDFormat() + + def testAccessors(self): + """Test for NameIDFormat accessors""" + self.name_id_format.text = saml.NAMEID_FORMAT_EMAILADDRESS + new_name_id_format = md.name_id_format_from_string( + self.name_id_format.to_string()) + assert new_name_id_format.text.strip() == saml.NAMEID_FORMAT_EMAILADDRESS + + def testUsingTestData(self): + """Test for name_id_format_from_string() using test data.""" + new_name_id_format = md.name_id_format_from_string( + md_data.TEST_NAME_ID_FORMAT) + assert new_name_id_format.text.strip() == saml.NAMEID_FORMAT_EMAILADDRESS + + +class TestSingleSignOnService: + + def setup_class(self): + self.endpoint = md.SingleSignOnService() + + def testAccessors(self): + """Test for SingelSignOnService accessors""" + self.endpoint.binding = saml2.BINDING_HTTP_POST + self.endpoint.location = "http://www.example.com/endpoint" + self.endpoint.response_location = "http://www.example.com/response" + new_endpoint = md.single_sign_on_service_from_string(self.endpoint.to_string()) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + + def testUsingTestData(self): + """Test for SingelSignOn_service_from_string() using test data.""" + new_endpoint = md.single_sign_on_service_from_string( + md_data.TEST_SINGLE_SIGN_ON_SERVICE) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + +class TestNameIDMappingService: + + def setup_class(self): + self.endpoint = md.NameIDMappingService() + + def testAccessors(self): + """Test for NameIDMappingService accessors""" + self.endpoint.binding = saml2.BINDING_HTTP_POST + self.endpoint.location = "http://www.example.com/endpoint" + self.endpoint.response_location = "http://www.example.com/response" + new_endpoint = md.name_id_mapping_service_from_string(self.endpoint.to_string()) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + + def testUsingTestData(self): + """Test for name_id_mapping_service_from_string() using test data.""" + new_endpoint = md.name_id_mapping_service_from_string( + md_data.TEST_NAME_ID_MAPPING_SERVICE) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + +class TestAssertionIDRequestService: + + def setup_class(self): + self.endpoint = md.AssertionIDRequestService() + + def testAccessors(self): + """Test for AssertionIDRequestService accessors""" + self.endpoint.binding = saml2.BINDING_HTTP_POST + self.endpoint.location = "http://www.example.com/endpoint" + self.endpoint.response_location = "http://www.example.com/response" + new_endpoint = md.assertion_id_request_service_from_string( + self.endpoint.to_string()) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + + def testUsingTestData(self): + """Test for assertion_id_request_service_from_string() using test data.""" + new_endpoint = md.assertion_id_request_service_from_string( + md_data.TEST_ASSERTION_ID_REQUEST_SERVICE) + assert new_endpoint.binding == saml2.BINDING_HTTP_POST + assert new_endpoint.location == "http://www.example.com/endpoint" + assert new_endpoint.response_location == "http://www.example.com/response" + +class TestAttributeProfile: + + def setup_class(self): + self.attribute_profile = md.AttributeProfile() + + def testAccessors(self): + """Test for AttributeProfile accessors""" + self.attribute_profile.text = saml.PROFILE_ATTRIBUTE_BASIC + new_attribute_profile = md.attribute_profile_from_string( + self.attribute_profile.to_string()) + assert new_attribute_profile.text.strip() == saml.PROFILE_ATTRIBUTE_BASIC + + def testUsingTestData(self): + """Test for name_id_format_from_string() using test data.""" + new_attribute_profile = md.attribute_profile_from_string( + md_data.TEST_ATTRIBUTE_PROFILE) + assert new_attribute_profile.text.strip() == saml.PROFILE_ATTRIBUTE_BASIC + + +class TestIDPSSODescriptor: + def setup_class(self): + self.idp_sso_descriptor = md.IDPSSODescriptor() + + def testAccessors(self): + """Test for IDPSSODescriptor accessors""" + self.idp_sso_descriptor.id = "ID" + self.idp_sso_descriptor.valid_until = "2008-09-14T01:05:02Z" + self.idp_sso_descriptor.cache_duration = "10:00:00:00" + self.idp_sso_descriptor.protocol_support_enumeration = \ + samlp.NAMESPACE + self.idp_sso_descriptor.error_url = "http://www.example.com/errorURL" + self.idp_sso_descriptor.signature = ds.Signature() + self.idp_sso_descriptor.extensions = md.Extensions() + self.idp_sso_descriptor.key_descriptor.append(md.key_descriptor_from_string( + md_data.TEST_KEY_DESCRIPTOR)) + self.idp_sso_descriptor.organization = md.Organization() + self.idp_sso_descriptor.contact_person.append(md.ContactPerson()) + self.idp_sso_descriptor.artifact_resolution_service.append( + md.ArtifactResolutionService()) + self.idp_sso_descriptor.single_logout_service.append( + md.SingleLogoutService()) + self.idp_sso_descriptor.manage_name_id_service.append( + md.ManageNameIDService()) + self.idp_sso_descriptor.name_id_format.append( + md.NameIDFormat()) + self.idp_sso_descriptor.want_authn_requests_signed = 'true' + self.idp_sso_descriptor.single_sign_on_service.append( + md.SingleSignOnService()) + self.idp_sso_descriptor.name_id_mapping_service.append( + md.NameIDMappingService()) + self.idp_sso_descriptor.assertion_id_request_service.append( + md.AssertionIDRequestService()) + self.idp_sso_descriptor.attribute_profile.append( + md.AttributeProfile()) + self.idp_sso_descriptor.attribute.append(saml.Attribute()) + + new_idp_sso_descriptor = md.idpsso_descriptor_from_string( + self.idp_sso_descriptor.to_string()) + assert new_idp_sso_descriptor.id == "ID" + assert new_idp_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_idp_sso_descriptor.cache_duration == "10:00:00:00" + assert new_idp_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE + assert new_idp_sso_descriptor.error_url == "http://www.example.com/errorURL" + assert isinstance(new_idp_sso_descriptor.signature, ds.Signature) + assert isinstance(new_idp_sso_descriptor.extensions, md.Extensions) + assert isinstance(new_idp_sso_descriptor.key_descriptor[0], + md.KeyDescriptor) + assert isinstance(new_idp_sso_descriptor.organization, + md.Organization) + assert isinstance(new_idp_sso_descriptor.contact_person[0], + md.ContactPerson) + assert isinstance( + new_idp_sso_descriptor.artifact_resolution_service[0], + md.ArtifactResolutionService) + assert isinstance(new_idp_sso_descriptor.single_logout_service[0], + md.SingleLogoutService) + assert isinstance(new_idp_sso_descriptor.manage_name_id_service[0], + md.ManageNameIDService) + assert isinstance(new_idp_sso_descriptor.name_id_format[0], + md.NameIDFormat) + assert new_idp_sso_descriptor.want_authn_requests_signed == "true" + assert isinstance(new_idp_sso_descriptor.single_sign_on_service[0], + md.SingleSignOnService) + assert isinstance(new_idp_sso_descriptor.name_id_mapping_service[0], + md.NameIDMappingService) + assert isinstance( + new_idp_sso_descriptor.assertion_id_request_service[0], + md.AssertionIDRequestService) + assert isinstance(new_idp_sso_descriptor.attribute_profile[0], + md.AttributeProfile) + assert isinstance(new_idp_sso_descriptor.attribute[0], + saml.Attribute) + + def testUsingTestData(self): + """Test for idpsso_descriptor_from_string() using test data.""" + new_idp_sso_descriptor = md.idpsso_descriptor_from_string( + md_data.TEST_IDP_SSO_DESCRIPTOR) + assert new_idp_sso_descriptor.id == "ID" + assert new_idp_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_idp_sso_descriptor.cache_duration == "10:00:00:00" + assert new_idp_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE + assert new_idp_sso_descriptor.error_url == "http://www.example.com/errorURL" + assert isinstance(new_idp_sso_descriptor.signature, ds.Signature) + assert isinstance(new_idp_sso_descriptor.extensions, md.Extensions) + assert isinstance(new_idp_sso_descriptor.key_descriptor[0], + md.KeyDescriptor) + assert isinstance(new_idp_sso_descriptor.organization, + md.Organization) + assert isinstance(new_idp_sso_descriptor.contact_person[0], + md.ContactPerson) + assert isinstance( + new_idp_sso_descriptor.artifact_resolution_service[0], + md.ArtifactResolutionService) + assert isinstance(new_idp_sso_descriptor.single_logout_service[0], + md.SingleLogoutService) + assert isinstance(new_idp_sso_descriptor.manage_name_id_service[0], + md.ManageNameIDService) + assert isinstance(new_idp_sso_descriptor.name_id_format[0], + md.NameIDFormat) + assert new_idp_sso_descriptor.want_authn_requests_signed == "true" + assert isinstance(new_idp_sso_descriptor.single_sign_on_service[0], + md.SingleSignOnService) + assert isinstance(new_idp_sso_descriptor.name_id_mapping_service[0], + md.NameIDMappingService) + assert isinstance( + new_idp_sso_descriptor.assertion_id_request_service[0], + md.AssertionIDRequestService) + assert isinstance(new_idp_sso_descriptor.attribute_profile[0], + md.AttributeProfile) + assert isinstance(new_idp_sso_descriptor.attribute[0], + saml.Attribute) + + +class TestAssertionConsumerService: + + def setup_class(self): + self.i_e = md.AssertionConsumerService() + + def testAccessors(self): + """Test for AssertionConsumerService accessors""" + self.i_e.binding = saml2.BINDING_HTTP_POST + self.i_e.location = "http://www.example.com/endpoint" + self.i_e.response_location = "http://www.example.com/response" + self.i_e.index = "1" + self.i_e.is_default = "false" + new_i_e = md.assertion_consumer_service_from_string(self.i_e.to_string()) + assert new_i_e.binding == saml2.BINDING_HTTP_POST + assert new_i_e.location == "http://www.example.com/endpoint" + assert new_i_e.response_location == "http://www.example.com/response" + assert new_i_e.index == "1" + assert new_i_e.is_default == "false" + + def testUsingTestData(self): + """Test for assertion_consumer_service_from_string() using test data.""" + new_i_e = md.assertion_consumer_service_from_string( + md_data.TEST_ASSERTION_CONSUMER_SERVICE) + assert new_i_e.binding == saml2.BINDING_HTTP_POST + assert new_i_e.location == "http://www.example.com/endpoint" + assert new_i_e.response_location == "http://www.example.com/response" + assert new_i_e.index == "1" + assert new_i_e.is_default == "false" + + +class TestRequestedAttribute: + + def setup_class(self): + self.requested_attribute = md.RequestedAttribute() + + def testAccessors(self): + """Test for RequestedAttribute accessors""" + assert isinstance(self.requested_attribute, saml.AttributeType) + assert isinstance(self.requested_attribute, md.RequestedAttribute) + assert self.requested_attribute.is_required is None + self.requested_attribute.is_required = "true" + new_requested_attribute = md.requested_attribute_from_string( + self.requested_attribute.to_string()) + assert new_requested_attribute.is_required == "true" + assert isinstance(new_requested_attribute, saml.AttributeType) + assert isinstance(new_requested_attribute, md.RequestedAttribute) + + def testUsingTestData(self): + """Test for requested_attribute_from_string() using test data.""" + new_requested_attribute = md.requested_attribute_from_string( + md_data.TEST_REQUESTED_ATTRIBUTE) + assert new_requested_attribute.is_required == "true" + assert isinstance(new_requested_attribute, saml.AttributeType) + assert isinstance(new_requested_attribute, md.RequestedAttribute) + + +class TestServiceName: + + def setup_class(self): + self.service_name = md.ServiceName() + + def testAccessors(self): + """Test for ServiceName accessors""" + self.service_name.lang = "en" + self.service_name.text = "SIOS mail" + new_service_name = md.service_name_from_string(self.service_name.to_string()) + assert new_service_name.lang == "en" + assert new_service_name.text.strip() == "SIOS mail" + + def testUsingTestData(self): + """Test for organization_name_from_string() using test data.""" + new_service_name = md.service_name_from_string(md_data.TEST_SERVICE_NAME) + assert new_service_name.lang == "en" + assert new_service_name.text.strip() == "Catalogix Whois" + + +class TestServiceDescription: + + def setup_class(self): + self.service_description = md.ServiceDescription() + + def testAccessors(self): + """Test for ServiceDescription accessors""" + self.service_description.lang = "en" + self.service_description.text = "SIOS mail service" + new_service_description = md.service_description_from_string( + self.service_description.to_string()) + assert new_service_description.lang == "en" + assert new_service_description.text.strip() == "SIOS mail service" + + def testUsingTestData(self): + """Test for organization_name_from_string() using test data.""" + new_service_description = md.service_description_from_string( + md_data.TEST_SERVICE_DESCRIPTION) + assert new_service_description.lang == "en" + assert new_service_description.text.strip() == "Catalogix Whois Service" + + +class TestAttributeConsumingService: + + def setup_class(self): + self.attribute_consuming_service = md.AttributeConsumingService() + + def testAccessors(self): + """Test for AttributeConsumingService accessors""" + self.attribute_consuming_service.service_name.append(md.ServiceName()) + self.attribute_consuming_service.service_description.append( + md.ServiceDescription()) + self.attribute_consuming_service.requested_attribute.append( + md.RequestedAttribute()) + self.attribute_consuming_service.index = "1" + self.attribute_consuming_service.is_default = "true" + + new_attribute_consuming_service = md.attribute_consuming_service_from_string( + self.attribute_consuming_service.to_string()) + assert new_attribute_consuming_service.index == "1" + assert new_attribute_consuming_service.is_default == "true" + assert isinstance(new_attribute_consuming_service.service_name[0], + md.ServiceName) + assert isinstance( + new_attribute_consuming_service.service_description[0], + md.ServiceDescription) + assert isinstance( + new_attribute_consuming_service.requested_attribute[0], + md.RequestedAttribute) + + def testUsingTestData(self): + """Test for attribute_consuming_service_from_string() using test data.""" + new_attribute_consuming_service = md.attribute_consuming_service_from_string( + md_data.TEST_ATTRIBUTE_CONSUMING_SERVICE) + assert new_attribute_consuming_service.index == "1" + assert new_attribute_consuming_service.is_default == "true" + assert isinstance(new_attribute_consuming_service.service_name[0], + md.ServiceName) + assert isinstance( + new_attribute_consuming_service.service_description[0], + md.ServiceDescription) + assert isinstance( + new_attribute_consuming_service.requested_attribute[0], + md.RequestedAttribute) + + +class TestSPSSODescriptor: + def setup_class(self): + self.sp_sso_descriptor = md.SPSSODescriptor() + + def testAccessors(self): + """Test for SPSSODescriptor accessors""" + self.sp_sso_descriptor.id = "ID" + self.sp_sso_descriptor.valid_until = "2008-09-14T01:05:02Z" + self.sp_sso_descriptor.cache_duration = "10:00:00:00" + self.sp_sso_descriptor.protocol_support_enumeration = \ + samlp.NAMESPACE + self.sp_sso_descriptor.error_url = "http://www.example.com/errorURL" + self.sp_sso_descriptor.signature = ds.Signature() + self.sp_sso_descriptor.extensions = md.Extensions() + self.sp_sso_descriptor.key_descriptor.append(md.key_descriptor_from_string( + md_data.TEST_KEY_DESCRIPTOR)) + self.sp_sso_descriptor.organization = md.Organization() + self.sp_sso_descriptor.contact_person.append(md.ContactPerson()) + self.sp_sso_descriptor.artifact_resolution_service.append( + md.ArtifactResolutionService()) + self.sp_sso_descriptor.single_logout_service.append( + md.SingleLogoutService()) + self.sp_sso_descriptor.manage_name_id_service.append( + md.ManageNameIDService()) + self.sp_sso_descriptor.name_id_format.append( + md.NameIDFormat()) + self.sp_sso_descriptor.authn_requests_signed = "true" + self.sp_sso_descriptor.want_assertions_signed = "true" + self.sp_sso_descriptor.assertion_consumer_service.append( + md.AssertionConsumerService()) + self.sp_sso_descriptor.attribute_consuming_service.append( + md.AttributeConsumingService()) + + print self.sp_sso_descriptor + new_sp_sso_descriptor = md.spsso_descriptor_from_string( + self.sp_sso_descriptor.to_string()) + print new_sp_sso_descriptor + assert new_sp_sso_descriptor.id == "ID" + assert new_sp_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_sp_sso_descriptor.cache_duration == "10:00:00:00" + assert new_sp_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE + assert new_sp_sso_descriptor.error_url == "http://www.example.com/errorURL" + assert isinstance(new_sp_sso_descriptor.signature, ds.Signature) + assert isinstance(new_sp_sso_descriptor.extensions, md.Extensions) + assert isinstance(new_sp_sso_descriptor.key_descriptor[0], + md.KeyDescriptor) + assert isinstance(new_sp_sso_descriptor.organization, + md.Organization) + assert isinstance(new_sp_sso_descriptor.contact_person[0], + md.ContactPerson) + assert isinstance( + new_sp_sso_descriptor.artifact_resolution_service[0], + md.ArtifactResolutionService) + assert isinstance(new_sp_sso_descriptor.single_logout_service[0], + md.SingleLogoutService) + assert isinstance(new_sp_sso_descriptor.manage_name_id_service[0], + md.ManageNameIDService) + assert isinstance(new_sp_sso_descriptor.name_id_format[0], + md.NameIDFormat) + assert new_sp_sso_descriptor.authn_requests_signed == "true" + assert new_sp_sso_descriptor.want_assertions_signed == "true" + assert isinstance( + new_sp_sso_descriptor.assertion_consumer_service[0], + md.AssertionConsumerService) + assert isinstance( + new_sp_sso_descriptor.attribute_consuming_service[0], + md.AttributeConsumingService) + + def testUsingTestData(self): + """Test for spsso_descriptor_from_string() using test data.""" + new_sp_sso_descriptor = md.spsso_descriptor_from_string( + md_data.TEST_SP_SSO_DESCRIPTOR) + assert new_sp_sso_descriptor.id == "ID" + assert new_sp_sso_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_sp_sso_descriptor.cache_duration == "10:00:00:00" + assert new_sp_sso_descriptor.protocol_support_enumeration == samlp.NAMESPACE + assert new_sp_sso_descriptor.error_url == "http://www.example.com/errorURL" + assert isinstance(new_sp_sso_descriptor.signature, ds.Signature) + assert isinstance(new_sp_sso_descriptor.extensions, md.Extensions) + print new_sp_sso_descriptor.extensions.__dict__ + assert len(new_sp_sso_descriptor.extensions.extension_elements) == 2 + for eelem in new_sp_sso_descriptor.extensions.extension_elements: + print "EE",eelem.__dict__ + dp = extension_element_to_element(eelem, idpdisc.ELEMENT_FROM_STRING, + idpdisc.NAMESPACE) + print "DP",dp.c_tag, dp.c_namespace,dp.__dict__ + assert isinstance(dp, idpdisc.DiscoveryResponse) + assert isinstance(new_sp_sso_descriptor.key_descriptor[0], + md.KeyDescriptor) + assert isinstance(new_sp_sso_descriptor.organization, + md.Organization) + assert isinstance(new_sp_sso_descriptor.contact_person[0], + md.ContactPerson) + assert isinstance( + new_sp_sso_descriptor.artifact_resolution_service[0], + md.ArtifactResolutionService) + assert isinstance(new_sp_sso_descriptor.single_logout_service[0], + md.SingleLogoutService) + assert isinstance(new_sp_sso_descriptor.manage_name_id_service[0], + md.ManageNameIDService) + assert isinstance(new_sp_sso_descriptor.name_id_format[0], + md.NameIDFormat) + assert new_sp_sso_descriptor.authn_requests_signed == "true" + assert new_sp_sso_descriptor.want_assertions_signed == "true" + assert isinstance( + new_sp_sso_descriptor.assertion_consumer_service[0], + md.AssertionConsumerService) + assert isinstance( + new_sp_sso_descriptor.attribute_consuming_service[0], + md.AttributeConsumingService) + + +class TestEntityDescriptor: + def setup_class(self): + self.entity_descriptor = md.EntityDescriptor() + + def testAccessors(self): + """Test for RoleDescriptor accessors""" + self.entity_descriptor.id = "ID" + self.entity_descriptor.entity_id = "entityID" + self.entity_descriptor.valid_until = "2008-09-14T01:05:02Z" + self.entity_descriptor.cache_duration = "10:00:00:00" + + self.entity_descriptor.signature = ds.Signature() + self.entity_descriptor.extensions = md.Extensions() + self.entity_descriptor.role_descriptor.append(md.RoleDescriptor()) + self.entity_descriptor.idpsso_descriptor.append(md.IDPSSODescriptor()) + self.entity_descriptor.spsso_descriptor.append(md.SPSSODescriptor()) + self.entity_descriptor.organization = md.Organization() + self.entity_descriptor.contact_person.append(md.ContactPerson()) + self.entity_descriptor.additional_metadata_location.append( + md.AdditionalMetadataLocation()) + + new_entity_descriptor = md.entity_descriptor_from_string( + self.entity_descriptor.to_string()) + assert new_entity_descriptor.id == "ID" + assert new_entity_descriptor.entity_id == "entityID" + assert new_entity_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_entity_descriptor.cache_duration == "10:00:00:00" + assert isinstance(new_entity_descriptor.signature, ds.Signature) + assert isinstance(new_entity_descriptor.extensions, md.Extensions) + assert isinstance(new_entity_descriptor.role_descriptor[0], + md.RoleDescriptor) + assert isinstance(new_entity_descriptor.idpsso_descriptor[0], + md.IDPSSODescriptor) + assert isinstance(new_entity_descriptor.spsso_descriptor[0], + md.SPSSODescriptor) + assert isinstance(new_entity_descriptor.organization[0], + md.Organization) + assert isinstance(new_entity_descriptor.contact_person[0], + md.ContactPerson) + assert isinstance( + new_entity_descriptor.additional_metadata_location[0], + md.AdditionalMetadataLocation) + + def testUsingTestData(self): + """Test for entity_descriptor_from_string() using test data.""" + new_entity_descriptor = md.entity_descriptor_from_string( + md_data.TEST_ENTITY_DESCRIPTOR) + assert new_entity_descriptor.id == "ID" + assert new_entity_descriptor.entity_id == "entityID" + assert new_entity_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_entity_descriptor.cache_duration == "10:00:00:00" + assert isinstance(new_entity_descriptor.signature, ds.Signature) + assert isinstance(new_entity_descriptor.extensions, md.Extensions) + assert isinstance(new_entity_descriptor.role_descriptor[0], + md.RoleDescriptor) + assert isinstance(new_entity_descriptor.idpsso_descriptor[0], + md.IDPSSODescriptor) + assert isinstance(new_entity_descriptor.spsso_descriptor[0], + md.SPSSODescriptor) + assert isinstance(new_entity_descriptor.organization[0], + md.Organization) + assert isinstance(new_entity_descriptor.contact_person[0], + md.ContactPerson) + assert isinstance(new_entity_descriptor.additional_metadata_location[0], + md.AdditionalMetadataLocation) + + +class TestEntitiesDescriptor: + def setup_class(self): + self.entities_descriptor = md.EntitiesDescriptor() + + def testAccessors(self): + """Test for EntitiesDescriptor accessors""" + self.entities_descriptor.id = "ID" + self.entities_descriptor.name = "name" + self.entities_descriptor.valid_until = "2008-09-14T01:05:02Z" + self.entities_descriptor.cache_duration = "10:00:00:00" + + self.entities_descriptor.signature = ds.Signature() + self.entities_descriptor.extensions = md.Extensions() + self.entities_descriptor.entity_descriptor.append(md.EntityDescriptor()) + self.entities_descriptor.entities_descriptor.append( + md.EntitiesDescriptor()) + + new_entities_descriptor = md.entities_descriptor_from_string( + self.entities_descriptor.to_string()) + assert new_entities_descriptor.id == "ID" + assert new_entities_descriptor.name == "name" + assert new_entities_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_entities_descriptor.cache_duration == "10:00:00:00" + assert isinstance(new_entities_descriptor.signature, ds.Signature) + assert isinstance(new_entities_descriptor.extensions, md.Extensions) + assert isinstance(new_entities_descriptor.entity_descriptor[0], + md.EntityDescriptor) + assert isinstance(new_entities_descriptor.entities_descriptor[0], + md.EntitiesDescriptor) + + def testUsingTestData(self): + """Test for entities_descriptor_from_string() using test data.""" + new_entities_descriptor = md.entities_descriptor_from_string( + md_data.TEST_ENTITIES_DESCRIPTOR) + assert new_entities_descriptor.id == "ID" + assert new_entities_descriptor.name == "name" + assert new_entities_descriptor.valid_until == "2008-09-14T01:05:02Z" + assert new_entities_descriptor.cache_duration == "10:00:00:00" + assert isinstance(new_entities_descriptor.signature, ds.Signature) + assert isinstance(new_entities_descriptor.extensions, md.Extensions) + assert isinstance(new_entities_descriptor.entity_descriptor[0], + md.EntityDescriptor) + assert isinstance(new_entities_descriptor.entities_descriptor[0], + md.EntitiesDescriptor) + + diff --git a/tests/test_12_s_utils.py b/tests/test_12_s_utils.py new file mode 100644 index 0000000..a89302a --- /dev/null +++ b/tests/test_12_s_utils.py @@ -0,0 +1,444 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import zlib +import base64 +import gzip + +from saml2 import make_instance +from saml2 import s_utils as utils +from saml2 import saml +from saml2 import samlp +from saml2 import md + +from saml2.s_utils import do_attribute_statement + +from saml2.sigver import make_temp + +from saml2.saml import Attribute, NAME_FORMAT_URI, AttributeValue + +from py.test import raises + +SUCCESS_STATUS = """ +""" + +ERROR_STATUS = """ +Error resolving principal""" + + +def _eq(l1,l2): + return set(l1) == set(l2) + +def _oeq(l1,l2): + if len(l1) != len(l2): + print "Different number of items" + return False + for item in l1: + if item not in l2: + print "%s not in l2" % (item,) + for ite in l2: + print "\t%s" % (ite,) + return False + return True + +def test_inflate_then_deflate(): + str = """Selma Lagerlöf (1858-1940) was born in Östra Emterwik, Värmland, + Sweden. She was brought up on Mårbacka, the family estate, which she did + not leave until 1881, when she went to a teachers' college at Stockholm""" + + interm = utils.deflate_and_base64_encode(str) + bis = utils.decode_base64_and_inflate(interm) + assert bis == str + +def test_status_success(): + status = utils.success_status_factory() + status_text = "%s" % status + assert status_text == SUCCESS_STATUS + assert status.status_code.value == samlp.STATUS_SUCCESS + +def test_error_status(): + status = utils.status_message_factory("Error resolving principal", + samlp.STATUS_UNKNOWN_PRINCIPAL, + samlp.STATUS_RESPONDER) + + status_text = "%s" % status + print status_text + assert status_text == ERROR_STATUS + +def test_status_from_exception(): + e = utils.UnknownPrincipal("Error resolving principal") + stat = utils.status_from_exception_factory(e) + status_text = "%s" % stat + print status_text + assert status_text == ERROR_STATUS + +def test_attribute_sn(): + attr = utils.do_attributes({"surName":("Jeter", "")}) + assert len(attr) == 1 + print attr + inst = attr[0] + assert inst.name == "surName" + assert len(inst.attribute_value) == 1 + av = inst.attribute_value[0] + assert av.text == "Jeter" + +def test_attribute_age(): + attr = utils.do_attributes({"age":(37, "")}) + + assert len(attr) == 1 + inst = attr[0] + print inst + assert inst.name == "age" + assert len(inst.attribute_value) == 1 + av = inst.attribute_value[0] + assert av.text == "37" + assert av.get_type() == "xs:integer" + +def test_attribute_onoff(): + attr = utils.do_attributes({"onoff":(False, "")}) + + assert len(attr) == 1 + inst = attr[0] + print inst + assert inst.name == "onoff" + assert len(inst.attribute_value) == 1 + av = inst.attribute_value[0] + assert av.text == "false" + assert av.get_type() == "xs:boolean" + +def test_attribute_base64(): + b64sl = base64.b64encode("Selma Lagerlöf") + attr = utils.do_attributes({"name":(b64sl, "xs:base64Binary")}) + + assert len(attr) == 1 + inst = attr[0] + print inst + assert inst.name == "name" + assert len(inst.attribute_value) == 1 + av = inst.attribute_value[0] + assert av.get_type() == "xs:base64Binary" + assert av.text.strip() == b64sl + +def test_attribute_statement(): + statement = do_attribute_statement({"surName":("Jeter", ""), + "givenName":("Derek", "")}) + print statement + assert statement.keyswv() == ["attribute"] + assert len(statement.attribute) == 2 + attr0 = statement.attribute[0] + assert _eq(attr0.keyswv(), ["name","attribute_value"]) + assert len(attr0.attribute_value) == 1 + attr1 = statement.attribute[1] + assert _eq(attr1.keyswv(), ["name","attribute_value"]) + assert len(attr1.attribute_value) == 1 + if attr0.name == "givenName": + assert attr0.attribute_value[0].text == "Derek" + assert attr1.name == "surName" + assert attr1.attribute_value[0].text == "Jeter" + else: + assert attr0.name == "surName" + assert attr0.attribute_value[0].text == "Jeter" + assert attr1.name == "givenName" + assert attr1.attribute_value[0].text == "Derek" + +def test_audience(): + aud_restr = utils.factory(saml.AudienceRestriction, + audience=utils.factory(saml.Audience,text="urn:foo:bar")) + + assert aud_restr.keyswv() == ["audience"] + assert aud_restr.audience.text == "urn:foo:bar" + +def test_conditions(): + conditions = utils.factory( saml.Conditions, + not_before="2009-10-30T07:58:10.852Z", + not_on_or_after="2009-10-30T08:03:10.852Z", + audience_restriction=[utils.factory(saml.AudienceRestriction, + audience=utils.factory(saml.Audience, + text="urn:foo:bar"))]) + + assert _eq(conditions.keyswv(), ["not_before", "not_on_or_after", + "audience_restriction"]) + assert conditions.not_before == "2009-10-30T07:58:10.852Z" + assert conditions.not_on_or_after == "2009-10-30T08:03:10.852Z" + assert conditions.audience_restriction[0].audience.text == "urn:foo:bar" + +def test_value_1(): + #FriendlyName="givenName" Name="urn:oid:2.5.4.42" + # NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" + attribute = utils.factory(saml.Attribute, name="urn:oid:2.5.4.42", + name_format=NAME_FORMAT_URI) + assert _eq(attribute.keyswv(),["name","name_format"]) + assert attribute.name == "urn:oid:2.5.4.42" + assert attribute.name_format == saml.NAME_FORMAT_URI + +def test_value_2(): + attribute = utils.factory(saml.Attribute, name="urn:oid:2.5.4.42", + name_format=NAME_FORMAT_URI, + friendly_name="givenName") + assert _eq(attribute.keyswv(),["name","name_format","friendly_name"]) + assert attribute.name == "urn:oid:2.5.4.42" + assert attribute.name_format == NAME_FORMAT_URI + assert attribute.friendly_name == "givenName" + +def test_value_3(): + attribute = utils.factory(saml.Attribute, + attribute_value=[utils.factory( + saml.AttributeValue, text="Derek")], + name="urn:oid:2.5.4.42", + name_format=NAME_FORMAT_URI, + friendly_name="givenName") + + assert _eq(attribute.keyswv(),["name", "name_format", + "friendly_name", "attribute_value"]) + assert attribute.name == "urn:oid:2.5.4.42" + assert attribute.name_format == NAME_FORMAT_URI + assert attribute.friendly_name == "givenName" + assert len(attribute.attribute_value) == 1 + assert attribute.attribute_value[0].text == "Derek" + +def test_value_4(): + attribute = utils.factory(saml.Attribute, + attribute_value=[utils.factory( + saml.AttributeValue, text="Derek")], + friendly_name="givenName") + + assert _eq(attribute.keyswv(),["friendly_name", "attribute_value"]) + assert attribute.friendly_name == "givenName" + assert len(attribute.attribute_value) == 1 + assert attribute.attribute_value[0].text == "Derek" + +def test_do_attribute_statement_0(): + statement = do_attribute_statement({"vo_attr":("foobar", "")}) + + assert statement.keyswv() == ["attribute"] + assert len(statement.attribute) == 1 + attr0 = statement.attribute[0] + assert _eq(attr0.keyswv(), ["name","attribute_value"]) + assert attr0.name == "vo_attr" + assert len(attr0.attribute_value) == 1 + assert attr0.attribute_value[0].text == "foobar" + +def test_do_attribute_statement(): + statement = do_attribute_statement({"surName":("Jeter", ""), + "givenName":(["Derek", + "Sanderson"], "")}) + + assert statement.keyswv() == ["attribute"] + assert len(statement.attribute) == 2 + attr0 = statement.attribute[0] + assert _eq(attr0.keyswv(), ["name","attribute_value"]) + attr1 = statement.attribute[1] + assert _eq(attr1.keyswv(), ["name","attribute_value"]) + if attr0.name == "givenName": + assert len(attr0.attribute_value) == 2 + assert _eq([av.text for av in attr0.attribute_value], + ["Derek","Sanderson"]) + assert attr1.name == "surName" + assert attr1.attribute_value[0].text == "Jeter" + assert len(attr1.attribute_value) == 1 + else: + assert attr0.name == "surName" + assert attr0.attribute_value[0].text == "Jeter" + assert len(attr0.attribute_value) == 1 + assert attr1.name == "givenName" + assert len(attr1.attribute_value) == 2 + assert _eq([av.text for av in attr1.attribute_value], + ["Derek","Sanderson"]) + +def test_do_attribute_statement_multi(): + statement = do_attribute_statement( + {( "urn:oid:1.3.6.1.4.1.5923.1.1.1.7", + "urn:oasis:names:tc:SAML:2.0:attrname-format:uri", + "eduPersonEntitlement"):("Jeter", "")}) + + assert statement.keyswv() == ["attribute"] + assert len(statement.attribute) + assert _eq(statement.attribute[0].keyswv(), + ["name","name_format","friendly_name","attribute_value"]) + attribute = statement.attribute[0] + assert attribute.name == "urn:oid:1.3.6.1.4.1.5923.1.1.1.7" + assert attribute.name_format == ( + "urn:oasis:names:tc:SAML:2.0:attrname-format:uri") + assert attribute.friendly_name == "eduPersonEntitlement" + +def test_subject(): + subject = utils.factory(saml.Subject, text="_aaa", + name_id=saml.NameID( + text=saml.NAMEID_FORMAT_TRANSIENT)) + + assert _eq(subject.keyswv(),["text", "name_id"]) + assert subject.text == "_aaa" + assert subject.name_id.text == saml.NAMEID_FORMAT_TRANSIENT + +# --------------------------------------------------------------------------- + +def test_parse_attribute_map(): + (forward, backward) = utils.parse_attribute_map(["attribute.map"]) + + assert _eq(forward.keys(), backward.values()) + assert _eq(forward.values(), backward.keys()) + print forward.keys() + assert _oeq(forward.keys(), [ + ('urn:oid:1.3.6.1.4.1.5923.1.1.1.7', NAME_FORMAT_URI), + ('urn:oid:0.9.2342.19200300.100.1.1', NAME_FORMAT_URI), + ('urn:oid:1.3.6.1.4.1.5923.1.1.1.1', NAME_FORMAT_URI), + ('urn:oid:2.5.4.42', NAME_FORMAT_URI), + ('urn:oid:2.5.4.4', NAME_FORMAT_URI), + ('urn:oid:0.9.2342.19200300.100.1.3', NAME_FORMAT_URI), + ('urn:oid:2.5.4.12', NAME_FORMAT_URI)]) + assert _eq(forward.keys(), [ + ('urn:oid:1.3.6.1.4.1.5923.1.1.1.7', NAME_FORMAT_URI), + ('urn:oid:0.9.2342.19200300.100.1.1', NAME_FORMAT_URI), + ('urn:oid:1.3.6.1.4.1.5923.1.1.1.1', NAME_FORMAT_URI), + ('urn:oid:2.5.4.42', NAME_FORMAT_URI), + ('urn:oid:2.5.4.4', NAME_FORMAT_URI), + ('urn:oid:0.9.2342.19200300.100.1.3', NAME_FORMAT_URI), + ('urn:oid:2.5.4.12', NAME_FORMAT_URI)]) + assert _eq(backward.keys(),["surName","givenName","title","uid","mail", + "eduPersonAffiliation", + "eduPersonEntitlement"]) + + +def test_identity_attribute_0(): + (forward, backward) = utils.parse_attribute_map(["attribute.map"]) + a = Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI, + friendly_name="surName") + + assert utils.identity_attribute("name",a,forward) == "urn:oid:2.5.4.4" + assert utils.identity_attribute("friendly",a,forward) == "surName" + +def test_identity_attribute_1(): + (forward, backward) = utils.parse_attribute_map(["attribute.map"]) + a = Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI) + + assert utils.identity_attribute("name",a,forward) == "urn:oid:2.5.4.4" + assert utils.identity_attribute("friendly",a,forward) == "surName" + +def test_identity_attribute_2(): + (forward, backward) = utils.parse_attribute_map(["attribute.map"]) + a = Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI) + + assert utils.identity_attribute("name",a,forward) == "urn:oid:2.5.4.5" + # if there would be a map it would be serialNumber + assert utils.identity_attribute("friendly",a,forward) == "urn:oid:2.5.4.5" + +def test_identity_attribute_3(): + a = Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI) + + assert utils.identity_attribute("name",a) == "urn:oid:2.5.4.5" + # if there would be a map it would be serialNumber + assert utils.identity_attribute("friendly",a) == "urn:oid:2.5.4.5" + +def test_identity_attribute_4(): + a = Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI, + friendly_name="serialNumber") + + assert utils.identity_attribute("name",a) == "urn:oid:2.5.4.5" + # if there would be a map it would be serialNumber + assert utils.identity_attribute("friendly",a) == "serialNumber" + +def _givenName(a): + assert a["name"] == "urn:oid:2.5.4.42" + assert a["friendly_name"] == "givenName" + assert len(a["attribute_value"]) == 1 + assert a["attribute_value"] == [{"text":"Derek"}] + +def _surName(a): + assert a["name"] == "urn:oid:2.5.4.4" + assert a["friendly_name"] == "surName" + assert len(a["attribute_value"]) == 1 + assert a["attribute_value"] == [{"text":"Jeter"}] + +def test_nameformat_email(): + assert utils.valid_email("foo@example.com") + assert utils.valid_email("a@b.com") + assert utils.valid_email("a@b.se") + assert utils.valid_email("john@doe@johndoe.com") == False + +def test_attribute(): + a = utils.factory(saml.Attribute, + friendly_name="eduPersonScopedAffiliation", + name="urn:oid:1.3.6.1.4.1.5923.1.1.1.9", + name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri") + + assert _eq(a.keyswv(), ["friendly_name","name", "name_format"]) + + a = utils.factory(saml.Attribute, + friendly_name="eduPersonScopedAffiliation", + name="urn:oid:1.3.6.1.4.1.5923.1.1.1.9", + name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri", + attribute_value=[saml.AttributeValue(text="member@example.com")]) + + assert _eq(a.keyswv(), ["friendly_name","name", "name_format", + "attribute_value"]) + +def test_attribute_statement(): + statement = utils.factory( saml.Statement, + attribute=[ + utils.factory(saml.Attribute, + attribute_value=[ + utils.factory( + saml.AttributeValue,text="Derek")], + friendly_name="givenName"), + utils.factory(saml.Attribute, + attribute_value=[ + utils.factory( + saml.AttributeValue,text="Jeter")], + friendly_name="surName"), + ]) + assert statement.keyswv() == ["attribute"] + assert len(statement.attribute) == 2 + +def test_subject_confirmation_data(): + s = utils.factory( saml.SubjectConfirmation, + in_response_to="_12345678", + not_before="2010-02-11T07:30:00Z", + not_on_or_after="2010-02-11T07:35:00Z", + recipient="http://example.com/sp/", + address="192.168.0.10") + + assert _eq(s.keyswv(),["in_response_to","not_before","not_on_or_after", + "recipient", "address"]) + +def test_subject_confirmation(): + s = utils.factory( saml.SubjectConfirmation, + method="urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser", + base_id="1234", + name_id="abcd", + subject_confirmation_data=utils.factory( + saml.SubjectConfirmationData, + in_response_to="_1234567890", + recipient="http://example.com/sp/")) + + assert _eq(s.keyswv(), + ["method","base_id","name_id","subject_confirmation_data"]) + assert s.method == "urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser" + + +def test_authn_context_class_ref(): + a = utils.factory( saml.AuthnContextClassRef, + text="urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified") + assert a.keyswv() == ["text"] + assert a.text == "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified" + +def test_authn_context(): + accr = utils.factory( saml.AuthnContext, + text="urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified") + a = utils.factory(saml.AuthnContext, authn_context_class_ref=accr) + + assert a.keyswv() == ["authn_context_class_ref"] + +def test_authn_statement(): + accr = utils.factory( saml.AuthnContextClassRef, + text="urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified") + ac = utils.factory( saml.AuthnContext, + authn_context_class_ref=accr) + ast = utils.factory( saml.AuthnStatement, + authn_instant="2010-03-10T12:33:00Z", + session_index="_12345", + session_not_on_or_after="2010-03-11T12:00:00Z", + authn_context=ac + ) + assert _eq(ast.keyswv(),["authn_instant","session_index", + "session_not_on_or_after", + "authn_context"]) diff --git a/tests/test_43_soap.py b/tests/test_43_soap.py new file mode 100755 index 0000000..f908cb6 --- /dev/null +++ b/tests/test_43_soap.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +try: + from xml.etree import cElementTree as ElementTree +except ImportError: + try: + import cElementTree as ElementTree + except ImportError: + from elementtree import ElementTree + +import saml2.samlp as samlp +from saml2.samlp import NAMESPACE as SAMLP_NAMESPACE + +NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/" + +example = """ + + + https://www.example.com/SAML + + + + + + + + + + +""" + +def test_parse_soap_envelope(): + envelope = ElementTree.fromstring(example) + assert envelope.tag == '{%s}Envelope' % NAMESPACE + # How to check that it's the right type ? + assert len(envelope) == 1 + body = envelope[0] + assert body.tag == '{%s}Body' % NAMESPACE + assert len(body) == 1 + saml_part = body[0] + assert saml_part.tag == '{%s}Response' % SAMLP_NAMESPACE + # {http://schemas.xmlsoap.org/soap/envelope/}Envelope + +def test_make_soap_envelope(): + envelope = ElementTree.Element('') + envelope.tag = '{%s}Envelope' % NAMESPACE + + body = ElementTree.Element('') + body.tag = '{%s}Body' % NAMESPACE + + envelope.append(body) + + request = samlp.AuthnRequest() + request.become_child_element_of(body) + + string = ElementTree.tostring(envelope, encoding="UTF-8") + result = """ +""" + assert string == result \ No newline at end of file