source: TI12-security/trunk/python/ndg.security.test/ndg/security/test/unit/x509/test_x509.py @ 5560

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.test/ndg/security/test/unit/x509/test_x509.py@5560
Revision 5560, 6.9 KB checked in by pjkersha, 10 years ago (diff)
  • Refactored unit tests for using Nose.
  • Added nosetests wrapper script - ndg.security.nosetests.sh and ini file nosetests.ini
  • Property svn:executable set to *
  • Property svn:keywords set to Id
Line 
1#!/usr/bin/env python
2"""NDG X509 Module unit tests
3
4NERC Data Grid Project
5"""
6__author__ = "P J Kershaw"
7__date__ = "03/01/07"
8__copyright__ = "(C) 2009 Science and Technology Facilities Council"
9__license__ = "BSD - see LICENSE file in top-level directory"
10__contact__ = "Philip.Kershaw@stfc.ac.uk"
11__revision__ = '$Id:test_x509.py 4335 2008-10-14 12:44:22Z pjkersha $'
12import logging
13logging.basicConfig(level=logging.DEBUG)
14log = logging.getLogger(__name__)
15
16import unittest
17import os
18import sys
19import getpass
20from StringIO import StringIO
21
22from os.path import expandvars as xpdVars
23from os.path import join as jnPath
24mkPath = lambda file: jnPath(os.environ['NDGSEC_X509_UNITTEST_DIR'], file)
25
26from ConfigParser import SafeConfigParser
27from ndg.security.test.unit import BaseTestCase
28
29import warnings
30_warningMsg = None
31_origWarn = warnings.warn
32def _warnWrapper(*arg, **kw):
33    global _warningMsg
34    _warningMsg = arg[0]
35    _origWarn(*arg, **kw)
36
37warnings.warn = _warnWrapper
38
39from ndg.security.common.X509 import X509CertRead, X509CertParse, X500DN, \
40    X509Stack, X509StackEmptyError, SelfSignedCert, X509CertIssuerNotFound
41
42class X509TestCase(BaseTestCase):
43   
44    def __del__(self):
45        warnings.warn = _origWarn
46        if getattr(super(X509TestCase, self), "__del__", None):
47            super(X509TestCase, self).__del__()
48       
49    def setUp(self):
50        super(X509TestCase, self).setUp()
51       
52        if 'NDGSEC_INT_DEBUG' in os.environ:
53            import pdb
54            pdb.set_trace()
55       
56        if 'NDGSEC_X509_UNITTEST_DIR' not in os.environ:
57            os.environ['NDGSEC_X509_UNITTEST_DIR'] = \
58                os.path.abspath(os.path.dirname(__file__))
59       
60        configParser = SafeConfigParser()
61        configFilePath = jnPath(os.environ['NDGSEC_X509_UNITTEST_DIR'],
62                                "x509Test.cfg")
63        configParser.read(configFilePath)
64       
65        self.cfg = {}
66        for section in configParser.sections():
67            self.cfg[section] = dict(configParser.items(section))
68       
69           
70    def test1X509CertRead(self):
71        'test1X509CertRead: read in a cert from file'
72        print(self.test1X509CertRead.__doc__)
73        self.x509Cert = \
74            X509CertRead(xpdVars(self.cfg['test1X509CertRead']['certfile']))
75        self.assert_(self.x509Cert)
76
77    def test2X509CertAsPEM(self):
78        'test2X509CertAsPEM: display as a PEM format string'
79        self.test1X509CertRead()
80        print(self.test2X509CertAsPEM.__doc__)
81        self.pemString = self.x509Cert.asPEM()
82        print(self.pemString)
83
84
85    def test3X509CertParse(self):
86        'test3X509CertParse: parse from a PEM format string'
87        self.test2X509CertAsPEM()
88        print(self.test3X509CertParse.__doc__)
89        self.assert_(X509CertParse(self.pemString))
90
91
92    def test4GetDN(self):
93        'test4GetDN: extract distinguished name'
94        self.test1X509CertRead()
95        print(self.test4GetDN.__doc__)
96        self.dn = self.x509Cert.dn
97        print(self.dn)
98       
99    def test5DN(self):
100        'test5DN: test X.500 Distinguished Name attributes'
101        print(self.test5DN.__doc__)
102        self.test4GetDN()
103        for item in self.dn.items():
104            print("%s=%s" % item)
105       
106    def test6DNCmp(self):
107        '''test6DNCmp: test X.500 Distinguished Name comparison
108        operators'''
109        print(self.test6DNCmp.__doc__)
110        self.test4GetDN()
111        testDN = X500DN(dn="/O=a/OU=b/CN=c")
112
113        self.assert_(not(testDN == self.dn))
114        self.assert_(testDN != self.dn)
115        self.assert_(self.dn == self.dn)
116        self.assert_(not(self.dn != self.dn))
117           
118    def test7X509Stack(self):
119        '''test7X509Stack: test X509Stack functionality'''
120        print(self.test7X509Stack.__doc__)
121        self.test1X509CertRead()
122        stack = X509Stack()
123        self.assert_(len(stack)==0)
124        self.assert_(stack.push(self.x509Cert))
125        self.assert_(len(stack)==1)
126        print("stack[0] = %s" % stack[0])
127        for i in stack:
128            print("stack iterator i = %s" % i)
129        print("stack.pop() = %s" % stack.pop())
130        self.assert_(len(stack)==0)
131           
132    def test8X509StackVerifyCertChain(self):
133        '''test8X509StackVerifyCertChain: testVerifyCertChain method'''
134        print(self.test8X509StackVerifyCertChain.__doc__)
135        self.test1X509CertRead()
136        proxyCert=X509CertRead(xpdVars(
137                   self.cfg['test8X509StackVerifyCertChain']['proxycertfile']))
138
139        stack1 = X509Stack()
140        stack1.push(self.x509Cert)
141       
142        caCert=X509CertRead(xpdVars(\
143                   self.cfg['test8X509StackVerifyCertChain']['cacertfile']))
144        caStack = X509Stack()
145        caStack.push(caCert)
146       
147        print("Verification of external cert with external CA stack...")
148        stack1.verifyCertChain(x509Cert2Verify=proxyCert, 
149                               caX509Stack=caStack)
150       
151        print("Verification of stack content using CA stack...")
152        stack1.push(proxyCert)
153        stack1.verifyCertChain(caX509Stack=caStack)
154       
155        print("Verification of stack alone...")
156        stack1.push(caCert)
157        stack1.verifyCertChain()
158       
159        print("Reject self-signed cert. ...")
160        stack2 = X509Stack()
161        try:
162            stack2.verifyCertChain()
163            self.fail("Empty stack error expected")
164        except X509StackEmptyError:
165            pass
166
167        stack2.push(caCert)
168        try:
169            stack2.verifyCertChain()
170            self.fail("Reject of self-signed cert. expected")
171        except SelfSignedCert:
172            pass
173       
174        print("Accept self-signed cert. ...")
175        stack2.verifyCertChain(rejectSelfSignedCert=False)
176       
177        self.assert_(stack2.pop())
178        print("Test no cert. issuer found ...")
179        stack2.push(proxyCert)
180        try:
181            stack2.verifyCertChain()
182            self.fail("No cert. issuer error expected")
183        except X509CertIssuerNotFound:
184            pass
185       
186        print("Test no cert. issuer found again with incomplete chain ...")
187        stack2.push(self.x509Cert)
188        try:
189            stack2.verifyCertChain()
190            self.fail("No cert. issuer error expected")
191        except X509CertIssuerNotFound:
192            pass
193
194    def test9ExpiryTime(self):
195        self.test1X509CertRead()
196       
197        # Set ridiculous bounds for expiry warning to ensure a warning message
198        # is output
199        self.assert_(self.x509Cert.isValidTime(
200                                            nDaysBeforeExpiryLimit=36500), 
201                                            "Certificate has expired")
202        if not _warningMsg:
203            self.fail("No warning message was set")
204        else:
205            print("PASSED - Got warning message from X509Cert."
206                  "isValidTime: %s" % _warningMsg)
207                                       
208if __name__ == "__main__":
209    unittest.main()
Note: See TracBrowser for help on using the repository browser.