[Python-modules-commits] [pyscard] 01/06: Imported Upstream version 1.9.4

Ludovic Rousseau rousseau at moszumanska.debian.org
Fri May 27 08:41:15 UTC 2016


This is an automated email from the git hooks/post-receive script.

rousseau pushed a commit to branch master
in repository pyscard.

commit 2bf0c16fcac0ce2152b71133dbd941a3522b67b9
Author: Ludovic Rousseau <rousseau at debian.org>
Date:   Fri May 27 09:43:10 2016 +0200

    Imported Upstream version 1.9.4
---
 ChangeLog                                          |   9 ++
 Makefile                                           |   3 +
 PKG-INFO                                           |   4 +-
 pyscard.egg-info/PKG-INFO                          |   4 +-
 pyscard.egg-info/SOURCES.txt                       |   2 +
 setup.py                                           |  46 +------
 smartcard/ATR.py                                   |  74 +++++-----
 smartcard/CardConnection.py                        |  10 ++
 smartcard/CardMonitoring.py                        |   5 +
 smartcard/Examples/scard-api/sample_getAttrib.py   |   4 +-
 smartcard/Examples/scard-api/sample_transaction.py |   3 +-
 smartcard/Examples/simple/getATR_context.py        |  49 +++++++
 smartcard/ExclusiveTransmitCardConnection.py       |   4 +-
 smartcard/pcsc/PCSCCardConnection.py               |   2 +-
 smartcard/scard/scard.i                            |   2 +-
 smartcard/util/__init__.py                         |   2 +-
 test/test_ATR.py                                   | 149 +++++++++++++++++++++
 test/test_util.py                                  |  80 +++++++++--
 18 files changed, 354 insertions(+), 98 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 02d5b86..ce3b87b 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,12 @@
+1.9.4 (May 2016)
+================
+    * Fix installation using pip and easy_install
+    * Avoid El Capitan SCardGetAttrib bug
+    * CardConnection: Add context management
+    * PCSCCardConnection: raise NoCardException if SCARD_E_NO_SMARTCARD
+    * Stop CardMonitor monitor thread after traceback print.
+    * minor improvements
+
 1.9.3 (March 2016)
 ==================
        * Fix SCardControl() on Windows 7
diff --git a/Makefile b/Makefile
index e3a7f6f..3a55691 100644
--- a/Makefile
+++ b/Makefile
@@ -18,4 +18,7 @@ pypi: clean
 test: build
 	$(PYTHON) setup.py test
 
+ChangeLog.git:
+	git log --stat --decorate=short > $@
+
 .PHONY: clean build pypi test
diff --git a/PKG-INFO b/PKG-INFO
index eccf328..a0946d4 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,12 +1,12 @@
 Metadata-Version: 1.1
 Name: pyscard
-Version: 1.9.3
+Version: 1.9.4
 Summary: Smartcard module for Python.
 Home-page: http://www.gemalto.com
 Author: Jean-Daniel Aussel
 Author-email: aussel.jean-daniel at gemalto.com
 License: GNU LESSER GENERAL PUBLIC LICENSE
-Download-URL: http://sourceforge.net/projects/pyscard/files/pyscard/pyscard%201.9.3/pyscard-1.9.3.tar.gz/download
+Download-URL: http://sourceforge.net/projects/pyscard/files/pyscard/pyscard%201.9.4/pyscard-1.9.4.tar.gz/download
 Description: Smartcard package for Python
 Platform: linux
 Platform: win32
diff --git a/pyscard.egg-info/PKG-INFO b/pyscard.egg-info/PKG-INFO
index eccf328..a0946d4 100644
--- a/pyscard.egg-info/PKG-INFO
+++ b/pyscard.egg-info/PKG-INFO
@@ -1,12 +1,12 @@
 Metadata-Version: 1.1
 Name: pyscard
-Version: 1.9.3
+Version: 1.9.4
 Summary: Smartcard module for Python.
 Home-page: http://www.gemalto.com
 Author: Jean-Daniel Aussel
 Author-email: aussel.jean-daniel at gemalto.com
 License: GNU LESSER GENERAL PUBLIC LICENSE
-Download-URL: http://sourceforge.net/projects/pyscard/files/pyscard/pyscard%201.9.3/pyscard-1.9.3.tar.gz/download
+Download-URL: http://sourceforge.net/projects/pyscard/files/pyscard/pyscard%201.9.4/pyscard-1.9.4.tar.gz/download
 Description: Smartcard package for Python
 Platform: linux
 Platform: win32
diff --git a/pyscard.egg-info/SOURCES.txt b/pyscard.egg-info/SOURCES.txt
index bd86597..f152b54 100644
--- a/pyscard.egg-info/SOURCES.txt
+++ b/pyscard.egg-info/SOURCES.txt
@@ -97,6 +97,7 @@ smartcard/Examples/scard-api/sample_readers.py
 smartcard/Examples/scard-api/sample_selectDFTelecom.py
 smartcard/Examples/scard-api/sample_transaction.py
 smartcard/Examples/simple/getATR.py
+smartcard/Examples/simple/getATR_context.py
 smartcard/Examples/simple/selectDF_TELECOM.py
 smartcard/Examples/simple/simpleAPDU.py
 smartcard/Examples/wx/apdumanager/SampleAPDUManagerPanel.py
@@ -162,4 +163,5 @@ smartcard/test/scard/testcase_transaction.py
 smartcard/test/scard/testsuite_scard.py
 smartcard/wx/resources/reader.ico
 smartcard/wx/resources/smartcard.ico
+test/test_ATR.py
 test/test_util.py
\ No newline at end of file
diff --git a/setup.py b/setup.py
index 97f260a..6e4a4e0 100755
--- a/setup.py
+++ b/setup.py
@@ -24,13 +24,10 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 """
 
 from distutils.util import get_platform
-import distutils.command.install as install_orig
-import inspect
 import sys
 
 from setuptools import setup, Extension
-from setuptools.command.bdist_egg import bdist_egg
-from setuptools.command.install import install
+from setuptools.command.build_py import build_py
 
 
 if sys.version_info[0:2] < (2, 6):
@@ -82,43 +79,17 @@ else:
     platform_extra_link_args = []   # ['-ggdb']
 
 
-VERSION_INFO = (1, 9, 3, 0)
+VERSION_INFO = (1, 9, 4, 0)
 VERSION_STR = '%i.%i.%i' % VERSION_INFO[:3]
 VERSION_ALT = '%i,%01i,%01i,%04i' % VERSION_INFO
 
 
-# Workaround for `pip install` and direct `setup.py install`
-class InstallBuildExtFirst(install):
-    """Workaround substitute `install` command"""
-    def run(self):
-        # Run built_ext first so that SWIG generated files are included
-        self.run_command("build_ext")
-        # Copy the rest of the logic from setuptools install so that the
-        # stack frame logic is preserved
-
-        # Explicit request for old-style install?  Just do it
-        if self.old_and_unmanageable or self.single_version_externally_managed:
-            return install_orig.install.run(self)
-
-        try:
-            have_called_from_setup = self._called_from_setup is not None
-        except AttributeError:
-            have_called_from_setup = False
-
-        if not have_called_from_setup or not self._called_from_setup(inspect.currentframe()):
-            # Run in backward-compatibility mode to support bdist_* commands.
-            install_orig.install.run(self)
-        else:
-            self.do_egg_install()
-
-
-# Workaround for `easy_install`
-class BdistEggBuildExtFirst(bdist_egg):
-    """Workaround substitute `bdist_egg` command"""
+class BuildPyBuildExtFirst(build_py):
+    """Workaround substitude `build_py` command for SWIG"""
     def run(self):
         # Run build_ext first so that SWIG generated files are included
-        self.run_command("build_ext")
-        return bdist_egg.run(self)
+        self.run_command('build_ext')
+        return build_py.run(self)
 
 
 kw = {'name': "pyscard",
@@ -144,10 +115,7 @@ kw = {'name': "pyscard",
                          "smartcard/wx": ["resources/*.ico"],
                        },
 
-      'cmdclass': {
-          'install': InstallBuildExtFirst,
-          'bdist_egg': BdistEggBuildExtFirst,
-      },
+      'cmdclass': {'build_py': BuildPyBuildExtFirst},
       # the _scard.pyd extension to build
       'ext_modules': [Extension("smartcard.scard._scard",
                              define_macros=[
diff --git a/smartcard/ATR.py b/smartcard/ATR.py
index c612e13..8c55d6e 100644
--- a/smartcard/ATR.py
+++ b/smartcard/ATR.py
@@ -26,13 +26,15 @@ from __future__ import print_function
 from smartcard.Exceptions import SmartcardException
 from smartcard.util import toHexString
 
+
 class ATR(object):
     """ATR class."""
 
     clockrateconversion = [372, 372, 558, 744, 1116, 1488, 1860, 'RFU',
-        'RFU', 512, 768, 1024, 1536, 2048, 'RFU', 'RFU', 'RFU']
+                           'RFU', 512, 768, 1024, 1536, 2048, 'RFU', 'RFU',
+                           'RFU']
     bitratefactor = ['RFU', 1, 2, 4, 8, 16, 32, 'RFU', 12, 20, 'RFU',
-        'RFU', 'RFU', 'RFU', 'RFU', 'RFU']
+                     'RFU', 'RFU', 'RFU', 'RFU', 'RFU']
     currenttable = [25, 50, 100, 'RFU']
 
     def __init__(self, bytes):
@@ -106,25 +108,25 @@ class ATR(object):
             if self.hasTB[n]:
                 self.TB[n] = self.bytes[offset + self.hasTA[n] + self.hasTB[n]]
             if self.hasTC[n]:
-                self.TC[n] = self.bytes[offset +\
-                             self.hasTA[n] +\
-                             self.hasTB[n] +\
-                             self.hasTC[n]]
+                self.TC[n] = self.bytes[offset +
+                                        self.hasTA[n] +
+                                        self.hasTB[n] +
+                                        self.hasTC[n]]
             if self.hasTD[n]:
-                self.TD[n] = self.bytes[offset +\
-                             self.hasTA[n] +\
-                             self.hasTB[n] +\
-                             self.hasTC[n] +\
-                             self.hasTD[n]]
+                self.TD[n] = self.bytes[offset +
+                                        self.hasTA[n] +
+                                        self.hasTB[n] +
+                                        self.hasTC[n] +
+                                        self.hasTD[n]]
 
             self.interfaceBytesCount += self.hasTA[n] +\
-                                        self.hasTB[n] +\
-                                        self.hasTC[n] +\
-                                        self.hasTD[n]
+                self.hasTB[n] +\
+                self.hasTC[n] +\
+                self.hasTD[n]
             TD = self.TD[n]
             hasTD = self.hasTD[n]
             offset = offset + self.hasTA[n] + self.hasTB[n] +\
-                              self.hasTC[n] + self.hasTD[n]
+                self.hasTC[n] + self.hasTD[n]
             n = n + 1
 
         # historical bytes
@@ -203,28 +205,28 @@ class ATR(object):
 
     def getBitRateFactor(self):
         """Return bit rate factor."""
-        if self.DI != None:
+        if self.DI is not None:
             return ATR.bitratefactor[self.DI]
         else:
             return 1
 
     def getClockRateConversion(self):
         """Return clock rate conversion."""
-        if self.FI != None:
+        if self.FI is not None:
             return ATR.clockrateconversion[self.FI]
         else:
             return 372
 
     def getProgrammingCurrent(self):
         """Return maximum programming current."""
-        if self.II != None:
+        if self.II is not None:
             return ATR.currenttable[self.II]
         else:
             return 50
 
     def getProgrammingVoltage(self):
         """Return programming voltage."""
-        if self.PI1 != None:
+        if self.PI1 is not None:
             return 5 * (1 + self.PI1)
         else:
             return 5
@@ -237,7 +239,7 @@ class ATR(object):
         """Returns a dictionnary of supported protocols."""
         protocols = {}
         for td in self.TD:
-            if td != None:
+            if td is not None:
                 strprotocol = "T=%d" % (td & 0x0F)
                 protocols[strprotocol] = True
         if not self.hasTD[0]:
@@ -263,25 +265,28 @@ class ATR(object):
         """Dump the details of an ATR."""
 
         for i in range(0, len(self.TA)):
-            if self.TA[i] != None:
+            if self.TA[i] is not None:
                 print("TA%d: %x" % (i + 1, self.TA[i]))
-            if self.TB[i] != None:
+            if self.TB[i] is not None:
                 print("TB%d: %x" % (i + 1, self.TB[i]))
-            if self.TC[i] != None:
+            if self.TC[i] is not None:
                 print("TC%d: %x" % (i + 1, self.TC[i]))
-            if self.TD[i] != None:
+            if self.TD[i] is not None:
                 print("TD%d: %x" % (i + 1, self.TD[i]))
 
         print('supported protocols ' + ','.join(self.getSupportedProtocols()))
         print('T=0 supported: ' + str(self.isT0Supported()))
         print('T=1 supported: ' + str(self.isT1Supported()))
 
-        print('checksum: ' + self.getChecksum())
+        if self.getChecksum():
+            print('checksum: %d' % self.getChecksum())
 
-        print('\tclock rate conversion factor: ' + str(self.getClockRateConversion()))
+        print('\tclock rate conversion factor: ' +
+              str(self.getClockRateConversion()))
         print('\tbit rate adjustment factor: ' + str(self.getBitRateFactor()))
 
-        print('\tmaximum programming current: ' + str(self.getProgrammingCurrent()))
+        print('\tmaximum programming current: ' +
+              str(self.getProgrammingCurrent()))
         print('\tprogramming voltage: ' + str(self.getProgrammingVoltage()))
 
         print('\tguard time: ' + str(self.getGuardTime()))
@@ -298,13 +303,13 @@ if __name__ == '__main__':
     """Small sample illustrating the use of ATR."""
 
     atrs = [[0x3F, 0x65, 0x25, 0x00, 0x2C, 0x09, 0x69, 0x90, 0x00],
-             [0x3F, 0x65, 0x25, 0x08, 0x93, 0x04, 0x6C, 0x90, 0x00],
-             [0x3B, 0x16, 0x94, 0x7C, 0x03, 0x01, 0x00, 0x00, 0x0D],
-             [0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03],
-             [0x3B, 0xE3, 0x00, 0xFF, 0x81, 0x31, 0x52, 0x45, 0xA1,
-                0xA2, 0xA3, 0x1B],
-             [0x3B, 0xE5, 0x00, 0x00, 0x81, 0x21, 0x45, 0x9C, 0x10,
-                0x01, 0x00, 0x80, 0x0D]]
+            [0x3F, 0x65, 0x25, 0x08, 0x93, 0x04, 0x6C, 0x90, 0x00],
+            [0x3B, 0x16, 0x94, 0x7C, 0x03, 0x01, 0x00, 0x00, 0x0D],
+            [0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03],
+            [0x3B, 0xE3, 0x00, 0xFF, 0x81, 0x31, 0x52, 0x45, 0xA1,
+             0xA2, 0xA3, 0x1B],
+            [0x3B, 0xE5, 0x00, 0x00, 0x81, 0x21, 0x45, 0x9C, 0x10,
+             0x01, 0x00, 0x80, 0x0D]]
 
     for atr in atrs:
         a = ATR(atr)
@@ -312,4 +317,3 @@ if __name__ == '__main__':
         print(a)
         a.dump()
         print(toHexString(a.getHistoricalBytes()))
-
diff --git a/smartcard/CardConnection.py b/smartcard/CardConnection.py
index 0e488ea..6ceea1b 100644
--- a/smartcard/CardConnection.py
+++ b/smartcard/CardConnection.py
@@ -210,3 +210,13 @@ class CardConnection(Observable):
 
         Subclasses must override this method for implementing get attrib."""
         pass
+
+    def __enter__(self):
+        """Enter the runtime context.
+        """
+        return self
+
+    def __exit__(self, type, value, traceback):
+        """Exit the runtime context trying to disconnect.
+        """
+        self.disconnect()
diff --git a/smartcard/CardMonitoring.py b/smartcard/CardMonitoring.py
index 5624456..6265eb5 100644
--- a/smartcard/CardMonitoring.py
+++ b/smartcard/CardMonitoring.py
@@ -189,6 +189,11 @@ class CardMonitoringThread(object):
                 except:
                     # FIXME Tighten the exceptions caught by this block
                     traceback.print_exc()
+                    # Most likely raised during interpreter shutdown due
+                    # to unclean exit which failed to remove all observers.
+                    # To solve this, we set the stop event and pass the
+                    # exception to let the thread finish gracefully.
+                    self.stopEvent.set()
 
         # stop the thread by signaling stopEvent
         def stop(self):
diff --git a/smartcard/Examples/scard-api/sample_getAttrib.py b/smartcard/Examples/scard-api/sample_getAttrib.py
index 7390b73..fb97f1d 100755
--- a/smartcard/Examples/scard-api/sample_getAttrib.py
+++ b/smartcard/Examples/scard-api/sample_getAttrib.py
@@ -109,9 +109,9 @@ if __name__ == '__main__':
 
         if len(readers) < 1:
             raise error('No smart card readers')
-        print('Trying to retreive attributes of', readers[0])
 
         for reader in readers:
+            print('Trying to retreive attributes of', reader)
             hresult, hcard, dwActiveProtocol = SCardConnect(
                 hcontext,
                 reader,
@@ -132,7 +132,7 @@ if __name__ == '__main__':
                             print('-----------------', \
                                 attributes[i], \
                                 '-----------------')
-                            print('unsupported')
+                            print('error:', SCardGetErrorMessage(hresult))
 
                 finally:
                     hresult = SCardDisconnect(hcard, SCARD_UNPOWER_CARD)
diff --git a/smartcard/Examples/scard-api/sample_transaction.py b/smartcard/Examples/scard-api/sample_transaction.py
index a4a0e2a..fbc6102 100755
--- a/smartcard/Examples/scard-api/sample_transaction.py
+++ b/smartcard/Examples/scard-api/sample_transaction.py
@@ -26,6 +26,7 @@ along with pyscard; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 """
 
+from __future__ import print_function
 from smartcard.scard import *
 
 try:
@@ -40,7 +41,7 @@ try:
         hresult, readers = SCardListReaders(hcontext, [])
         if hresult != SCARD_S_SUCCESS:
             raise error(
-                'Failed to list readers:: ' + \
+                'Failed to list readers: ' + \
                 SCardGetErrorMessage(hresult))
         print('PCSC Readers:', readers)
 
diff --git a/smartcard/Examples/simple/getATR_context.py b/smartcard/Examples/simple/getATR_context.py
new file mode 100755
index 0000000..ccb7aca
--- /dev/null
+++ b/smartcard/Examples/simple/getATR_context.py
@@ -0,0 +1,49 @@
+#! /usr/bin/env python
+"""
+Sample script that displays the ATR of inserted cards.
+
+__author__ = "http://www.gemalto.com"
+
+Copyright 2001-2012 gemalto
+Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel at gemalto.com
+Copyright 2010 Ludovic Rousseau
+Author: Ludovic Rousseau, mailto:ludovic.rousseau at free.fr
+
+This file is part of pyscard.
+
+pyscard is free software; you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation; either version 2.1 of the License, or
+(at your option) any later version.
+
+pyscard is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with pyscard; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+"""
+from __future__ import print_function
+from smartcard.Exceptions import NoCardException
+from smartcard.System import readers
+from smartcard.util import toHexString
+
+# Use a connection context
+# the connection object is automatically destroyed at the end of with block
+
+for reader in readers():
+    with reader.createConnection() as connection:
+        try:
+            connection.connect()
+            print(reader, toHexString(connection.getATR()))
+        except NoCardException:
+            print(reader, 'no card inserted')
+
+#sleep(5)
+
+import sys
+if 'win32' == sys.platform:
+    print('press Enter to continue')
+    sys.stdin.read(1)
diff --git a/smartcard/ExclusiveTransmitCardConnection.py b/smartcard/ExclusiveTransmitCardConnection.py
index 1d5b229..a57073c 100644
--- a/smartcard/ExclusiveTransmitCardConnection.py
+++ b/smartcard/ExclusiveTransmitCardConnection.py
@@ -49,7 +49,7 @@ class ExclusiveTransmitCardConnection(CardConnectionDecorator):
                 hresult = SCardBeginTransaction(component.hcard)
                 if 0 != hresult:
                     raise CardConnectionException(
-                        'Failed to lock with SCardBeginTransaction' +\
+                        'Failed to lock with SCardBeginTransaction: ' +\
                         SCardGetErrorMessage(hresult))
                 else:
                     #print('locked')
@@ -71,7 +71,7 @@ class ExclusiveTransmitCardConnection(CardConnectionDecorator):
                                               SCARD_LEAVE_CARD)
                 if 0 != hresult:
                     raise CardConnectionException(
-                        'Failed to unlock with SCardEndTransaction' +\
+                        'Failed to unlock with SCardEndTransaction: ' +\
                         SCardGetErrorMessage(hresult))
                 else:
                     #print('unlocked')
diff --git a/smartcard/pcsc/PCSCCardConnection.py b/smartcard/pcsc/PCSCCardConnection.py
index a3bd7a0..7eb2a48 100644
--- a/smartcard/pcsc/PCSCCardConnection.py
+++ b/smartcard/pcsc/PCSCCardConnection.py
@@ -117,7 +117,7 @@ class PCSCCardConnection(CardConnection):
             self.hcontext, str(self.reader), mode, pcscprotocol)
         if hresult != 0:
             self.hcard = None
-            if SCARD_W_REMOVED_CARD == hresult:
+            if hresult in (SCARD_W_REMOVED_CARD, SCARD_E_NO_SMARTCARD):
                 raise NoCardException(
                     'Unable to connect: ' + \
                     SCardGetErrorMessage(hresult))
diff --git a/smartcard/scard/scard.i b/smartcard/scard/scard.i
index 74c6104..76f63ad 100644
--- a/smartcard/scard/scard.i
+++ b/smartcard/scard/scard.i
@@ -346,7 +346,7 @@ static SCARDRETCODE _GetAttrib(SCARDHANDLE hcard, SCARDDWORDARG dwAttrId, BYTELI
 {
     long lRetCode;
 
-    pbl->cBytes = 0;
+    pbl->cBytes = 65535;
     pbl->ab = NULL;
 
     lRetCode = (mySCardGetAttrib)(hcard, dwAttrId, pbl->ab, &pbl->cBytes);
diff --git a/smartcard/util/__init__.py b/smartcard/util/__init__.py
index 242d1c3..08da8b2 100644
--- a/smartcard/util/__init__.py
+++ b/smartcard/util/__init__.py
@@ -100,7 +100,7 @@ def toBytes(bytestring):
     packedstring = bytestring.replace(' ', '').replace('	','').replace('\n', '')
     try:
         return list(map(lambda x: int(''.join(x), 16), zip(*[iter(packedstring)] * 2)))
-    except KeyError:
+    except (KeyError, ValueError):
         raise TypeError('not a string representing a list of bytes')
 
 
diff --git a/test/test_ATR.py b/test/test_ATR.py
new file mode 100644
index 0000000..52f8c74
--- /dev/null
+++ b/test/test_ATR.py
@@ -0,0 +1,149 @@
+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import sys
+import unittest
+if sys.version_info >= (3, 0):
+    from io import StringIO
+else:
+    from StringIO import StringIO
+from smartcard.ATR import ATR
+
+
+class TestUtil(unittest.TestCase):
+
+    def setUp(self):
+        self.held, sys.stdout = sys.stdout, StringIO()
+
+    def test_ATR1(self):
+        atr = [0x3F, 0x65, 0x25, 0x00, 0x2C, 0x09, 0x69, 0x90, 0x00]
+        data_out = """TB1: 25
+TC1: 0
+supported protocols T=0
+T=0 supported: True
+T=1 supported: False
+	clock rate conversion factor: 372
+	bit rate adjustment factor: 1
+	maximum programming current: 50
+	programming voltage: 30
+	guard time: 0
+nb of interface bytes: 2
+nb of historical bytes: 5
+"""
+        a = ATR(atr)
+        a.dump()
+        output = sys.stdout.getvalue()
+        self.assertEqual(output, data_out)
+
+    def test_ATR2(self):
+        atr = [0x3F, 0x65, 0x25, 0x08, 0x93, 0x04, 0x6C, 0x90, 0x00]
+        data_out = """TB1: 25
+TC1: 8
+supported protocols T=0
+T=0 supported: True
+T=1 supported: False
+	clock rate conversion factor: 372
+	bit rate adjustment factor: 1
+	maximum programming current: 50
+	programming voltage: 30
+	guard time: 8
+nb of interface bytes: 2
+nb of historical bytes: 5
+"""
+        a = ATR(atr)
+        a.dump()
+        output = sys.stdout.getvalue()
+        self.assertEqual(output, data_out)
+
+    def test_ATR3(self):
+        atr = [0x3B, 0x16, 0x94, 0x7C, 0x03, 0x01, 0x00, 0x00, 0x0D]
+        data_out = """TA1: 94
+supported protocols T=0
+T=0 supported: True
+T=1 supported: False
+	clock rate conversion factor: 512
+	bit rate adjustment factor: 8
+	maximum programming current: 50
+	programming voltage: 5
+	guard time: None
+nb of interface bytes: 1
+nb of historical bytes: 6
+"""
+        a = ATR(atr)
+        a.dump()
+        output = sys.stdout.getvalue()
+        self.assertEqual(output, data_out)
+
+    def test_ATR4(self):
+        atr = [0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03]
+        data_out = """TB1: 0
+TC1: 0
+supported protocols T=0
+T=0 supported: True
+T=1 supported: False
+	clock rate conversion factor: 372
+	bit rate adjustment factor: 1
+	maximum programming current: 25
+	programming voltage: 5
+	guard time: 0
+nb of interface bytes: 2
+nb of historical bytes: 5
+"""
+        a = ATR(atr)
+        a.dump()
+        output = sys.stdout.getvalue()
+        self.assertEqual(output, data_out)
+
+    def test_ATR5(self):
+        atr = [0x3B, 0xE3, 0x00, 0xFF, 0x81, 0x31, 0x52, 0x45, 0xA1,
+               0xA2, 0xA3, 0x1B]
+        data_out = """TB1: 0
+TC1: ff
+TD1: 81
+TD2: 31
+TA3: 52
+TB3: 45
+supported protocols T=1
+T=0 supported: False
+T=1 supported: True
+checksum: 27
+	clock rate conversion factor: 372
+	bit rate adjustment factor: 1
+	maximum programming current: 25
+	programming voltage: 5
+	guard time: 255
+nb of interface bytes: 6
+nb of historical bytes: 3
+"""
+        a = ATR(atr)
+        a.dump()
+        output = sys.stdout.getvalue()
+        self.assertEqual(output, data_out)
+
+    def test_ATR6(self):
+        atr = [0x3B, 0xE5, 0x00, 0x00, 0x81, 0x21, 0x45, 0x9C, 0x10,
+               0x01, 0x00, 0x80, 0x0D]
+        data_out = """TB1: 0
+TC1: 0
+TD1: 81
+TD2: 21
+TB3: 45
+supported protocols T=1
+T=0 supported: False
+T=1 supported: True
+checksum: 13
+	clock rate conversion factor: 372
+	bit rate adjustment factor: 1
+	maximum programming current: 25
+	programming voltage: 5
+	guard time: 0
+nb of interface bytes: 5
+nb of historical bytes: 5
+"""
+        a = ATR(atr)
+        a.dump()
+        output = sys.stdout.getvalue()
+        self.assertEqual(output, data_out)
+
+if __name__ == '__main__':
+    unittest.main(buffer=True)
diff --git a/test/test_util.py b/test/test_util.py
index da6b5c9..5d71ce8 100644
--- a/test/test_util.py
+++ b/test/test_util.py
@@ -8,8 +8,9 @@
 import unittest
 from smartcard.util import *
 
+
 class TestUtil(unittest.TestCase):
-    
+
     def test_toBytes(self):
         data_in = "3B 65 00 00 9C 11 01 01 03"
         data_out = [59, 101, 0, 0, 156, 17, 1, 1, 3]
@@ -28,55 +29,110 @@ class TestUtil(unittest.TestCase):
                   '''
         self.assertEqual(toBytes(data_in), data_out)
 
+        data_in = "zz"
+        self.assertRaises(TypeError, toBytes, data_in)
+
     def test_padd(self):
         data_in = toBytes("3B 65 00 00 9C 11 01 01 03")
         data_out = [0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3,
-          0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
+                    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
         self.assertEqual(padd(data_in, 16), data_out)
 
-
     def test_toASCIIBytes(self):
         data_in = "Number 101"
-        data_out = [ 0x4E, 0x75, 0x6D, 0x62, 0x65, 0x72, 0x20, 0x31, 0x30, 0x31 ]
+        data_out = [0x4E, 0x75, 0x6D, 0x62, 0x65, 0x72, 0x20, 0x31, 0x30, 0x31]
         self.assertEqual(toASCIIBytes(data_in), data_out)
 
-
     def test_toASCIIString(self):
-        data_in = [0x4E,0x75,0x6D,0x62,0x65,0x72,0x20,0x31,0x30,0x31]
+        data_in = [0x4E, 0x75, 0x6D, 0x62, 0x65, 0x72, 0x20, 0x31, 0x30, 0x31]
         data_out = "Number 101"
         self.assertEqual(toASCIIString(data_in), data_out)
 
-
     def test_toGSM3_38Bytes(self):
         data_in = "@Pascal"
-        data_out = [ 0x00, 0x50, 0x61, 0x73, 0x63, 0x61, 0x6C ]
+        data_out = [0x00, 0x50, 0x61, 0x73, 0x63, 0x61, 0x6C]
         self.assertEqual(toGSM3_38Bytes(data_in), data_out)
 
         data_in = u"@ùPascal"
-        data_out = [ 0x00, 0x06, 0x50, 0x61, 0x73, 0x63, 0x61, 0x6C ]
+        data_out = [0x00, 0x06, 0x50, 0x61, 0x73, 0x63, 0x61, 0x6C]
         self.assertEqual(toGSM3_38Bytes(data_in), data_out)
 
         data_in = u"@ùPascal".encode('iso8859-1')
-        data_out = [ 0x00, 0x06, 0x50, 0x61, 0x73, 0x63, 0x61, 0x6C ]
+        data_out = [0x00, 0x06, 0x50, 0x61, 0x73, 0x63, 0x61, 0x6C]
+        self.assertEqual(toGSM3_38Bytes(data_in), data_out)
+
+        data_in = "1234"
+        data_out = [0x31, 0x32, 0x33, 0x34]
         self.assertEqual(toGSM3_38Bytes(data_in), data_out)
 
     def test_toHexString(self):
-        data_in = [ 0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03 ]
+        data_in = []
+        data_out = ""
+        self.assertEqual(toHexString(data_in), data_out)
+
+        data_in = 42
+        self.assertRaises(TypeError, toHexString, data_in)
+
+        data_in = [0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03]
         data_out = "3B 65 00 00 9C 11 01 01 03"
         self.assertEqual(toHexString(data_in), data_out)
 
+        data_out = "3B, 65, 00, 00, 9C, 11, 01, 01, 03"
+        self.assertEqual(toHexString(data_in, COMMA), data_out)
+
+        data_out = "0x3B 0x65 0x00 0x00 0x9C 0x11 0x01 0x01 0x03"
+        self.assertEqual(toHexString(data_in, HEX), data_out)
+
+        data_out = "0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03"
+        self.assertEqual(toHexString(data_in, HEX | COMMA), data_out)
+
+        data_out = "0X3B 0X65 0X00 0X00 0X9C 0X11 0X01 0X01 0X03"
+        self.assertEqual(toHexString(data_in, HEX | UPPERCASE), data_out)
+
+        data_out = "0X3B, 0X65, 0X00, 0X00, 0X9C, 0X11, 0X01, 0X01, 0X03"
+        self.assertEqual(toHexString(data_in, HEX | UPPERCASE | COMMA),
+                         data_out)
+
+        data_out = "3B6500009C11010103"
+        self.assertEqual(toHexString(data_in, PACK), data_out)
+
+        data_out = "3B,65,00,00,9C,11,01,01,03"
+        self.assertEqual(toHexString(data_in, COMMA | PACK), data_out)
+
+        data_out = "0x3B0x650x000x000x9C0x110x010x010x03"
+        self.assertEqual(toHexString(data_in, HEX | PACK), data_out)
+
+        data_out = "0x3B,0x65,0x00,0x00,0x9C,0x11,0x01,0x01,0x03"
+        self.assertEqual(toHexString(data_in, HEX | COMMA | PACK), data_out)
+
+        data_out = "0X3B0X650X000X000X9C0X110X010X010X03"
+        self.assertEqual(toHexString(data_in, HEX | UPPERCASE | PACK),
+                         data_out)
+
+        data_out = "0X3B,0X65,0X00,0X00,0X9C,0X11,0X01,0X01,0X03"
+        self.assertEqual(toHexString(data_in, HEX | UPPERCASE | COMMA |
+                                     PACK), data_out)
 
     def test_HexListToBinString(self):
         data_in = [1, 2, 3]
         data_out = "\x01\x02\x03"
         self.assertEqual(HexListToBinString(data_in), data_out)
 
-
     def test_BinStringToHexList(self):
         data_in = "\x01\x02\x03"
         data_out = [1, 2, 3]
         self.assertEqual(BinStringToHexList(data_in), data_out)
 
+    def test_hl2bs(self):
+        data_in = [78, 117, 109, 98, 101, 114, 32, 49, 48, 49]
+        data_out = 'Number 101'
+        self.assertEqual(hl2bs(data_in), data_out)
+
+    def test_bs2hl(self):
+        data_in = 'Number 101'
+        data_out = [78, 117, 109, 98, 101, 114, 32, 49, 48, 49]
+        self.assertEqual(bs2hl(data_in), data_out)
+
 
 if __name__ == '__main__':
     unittest.main()

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/pyscard.git



More information about the Python-modules-commits mailing list