[Python-modules-commits] [keyrings.alt] 11/14: Port tests from keyring 7.3

Dmitry Shachnev mitya57 at moszumanska.debian.org
Wed Mar 2 07:21:14 UTC 2016


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

mitya57 pushed a commit to tag 1.0
in repository keyrings.alt.

commit b73375a3e769314483a828e52de4f803bcd80842
Author: Jason R. Coombs <jaraco at jaraco.com>
Date:   Thu Jan 14 06:30:26 2016 -0500

    Port tests from keyring 7.3
---
 tests/__init__.py     |   0
 tests/test_Gnome.py   |  35 ++++++
 tests/test_Google.py  | 331 ++++++++++++++++++++++++++++++++++++++++++++++++++
 tests/test_Windows.py |  49 ++++++++
 tests/test_crypto.py  |  32 +++++
 tests/test_file.py    |  52 ++++++++
 tests/test_keyczar.py |  76 ++++++++++++
 tests/test_kwallet.py |  81 ++++++++++++
 tests/test_multi.py   |  58 +++++++++
 tests/test_pyfs.py    | 136 +++++++++++++++++++++
 10 files changed, 850 insertions(+)

diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/test_Gnome.py b/tests/test_Gnome.py
new file mode 100644
index 0000000..0d2117e
--- /dev/null
+++ b/tests/test_Gnome.py
@@ -0,0 +1,35 @@
+import types
+import sys
+import unittest
+
+from keyring.tests.test_backend import BackendBasicTests
+from keyring.tests.util import NoNoneDictMutator
+from keyrings.alt import Gnome
+
+
+def ImportBlesser(*names, **changes):
+    """A context manager to temporarily make it possible to import a module"""
+    for name in names:
+        changes[name] = types.ModuleType(name)
+    return NoNoneDictMutator(sys.modules, **changes)
+
+
+ at unittest.skipUnless(Gnome.Keyring.viable, "Need GnomeKeyring")
+class GnomeKeyringTestCase(BackendBasicTests, unittest.TestCase):
+
+    def init_keyring(self):
+        k = Gnome.Keyring()
+
+        # Store passwords in the session (in-memory) keyring for the tests. This
+        # is going to be automatically cleared when the user logoff.
+        k.KEYRING_NAME = 'session'
+
+        return k
+
+    def test_supported(self):
+        with ImportBlesser('gi.repository'):
+            self.assertTrue(Gnome.Keyring.viable)
+
+    def test_supported_no_module(self):
+        with NoNoneDictMutator(Gnome.__dict__, GnomeKeyring=None):
+            self.assertFalse(Gnome.Keyring.viable)
diff --git a/tests/test_Google.py b/tests/test_Google.py
new file mode 100644
index 0000000..339c191
--- /dev/null
+++ b/tests/test_Google.py
@@ -0,0 +1,331 @@
+import codecs
+import base64
+import unittest
+
+from keyring.tests.test_backend import BackendBasicTests
+from keyrings.alt import Google
+from keyring.credentials import SimpleCredential
+from keyring.backend import NullCrypter
+from keyring import errors
+from keyring.py27compat import input, pickle
+from keyring.tests import mocks
+
+def is_gdata_supported():
+    try:
+        __import__('gdata.service')
+    except ImportError:
+        return False
+    return True
+
+def init_google_docs_keyring(client, can_create=True,
+                             input_getter=input):
+    credentials = SimpleCredential('foo', 'bar')
+    return Google.DocsKeyring(credentials,
+                                             'test_src',
+                                             NullCrypter(),
+                                             client=client,
+                                             can_create=can_create,
+                                             input_getter=input_getter
+                                            )
+
+ at unittest.skipUnless(is_gdata_supported(),
+                     "Need Google Docs (gdata)")
+class GoogleDocsKeyringTestCase(BackendBasicTests, unittest.TestCase):
+    """Run all the standard tests on a new keyring"""
+
+    def init_keyring(self):
+        client = mocks.MockDocumentService()
+        client.SetClientLoginToken('foo')
+        return init_google_docs_keyring(client)
+
+ at unittest.skipUnless(is_gdata_supported(),
+                     "Need Google Docs (gdata)")
+class GoogleDocsKeyringInteractionTestCase(unittest.TestCase):
+    """Additional tests for Google Doc interactions"""
+
+    def _init_client(self, set_token=True):
+        client = mocks.MockDocumentService()
+        if set_token:
+            client.SetClientLoginToken('interaction')
+        return client
+
+    def _init_keyring(self, client):
+        self.keyring = init_google_docs_keyring(client)
+
+    def _init_listfeed(self):
+        listfeed = mocks.MockListFeed()
+        listfeed._entry = [mocks.MockDocumentListEntry(),
+                           mocks.MockDocumentListEntry()
+                          ]
+        return listfeed
+
+    def _encode_data(self, data):
+        return base64.urlsafe_b64encode(pickle.dumps(data))
+
+    def test_handles_auth_failure(self):
+        import gdata
+        client = self._init_client(set_token=False)
+        client._login_err = gdata.service.BadAuthentication
+        self._init_keyring(client)
+        with self.assertRaises(errors.InitError):
+            self.keyring.client
+
+    def test_handles_auth_error(self):
+        import gdata
+        client = self._init_client(set_token=False)
+        client._login_err = gdata.service.Error
+        self._init_keyring(client)
+        with self.assertRaises(errors.InitError):
+            self.keyring.client
+
+    def test_handles_login_captcha(self):
+        import gdata
+        client = self._init_client(set_token=False)
+        client._login_err = gdata.service.CaptchaRequired
+        client.captcha_url = 'a_captcha_url'
+        client.captcha_token = 'token'
+        self.get_input_called = False
+        def _get_input(prompt):
+            self.get_input_called = True
+            delattr(client, '_login_err')
+            return 'Foo'
+        self.keyring = init_google_docs_keyring(client, input_getter=_get_input)
+        self.keyring.client
+        self.assertTrue(self.get_input_called, 'Should have got input')
+
+    def test_retrieves_existing_keyring_with_and_without_bom(self):
+        client = self._init_client()
+        dummy_entries = dict(section1=dict(user1='pwd1'))
+        no_utf8_bom_entries = self._encode_data(dummy_entries)
+        client._request_response = dict(status=200, data=no_utf8_bom_entries)
+        client._listfeed = self._init_listfeed()
+        self._init_keyring(client)
+        self.assertEqual(self.keyring.get_password('section1', 'user1'), 'pwd1')
+
+        utf8_bom_entries = codecs.BOM_UTF8 + no_utf8_bom_entries
+        client._request_response = dict(status=200, data=utf8_bom_entries)
+        self._init_keyring(client)
+        self.assertEqual(self.keyring.get_password('section1', 'user1'), 'pwd1')
+
+    def test_handles_retrieve_failure(self):
+        client = self._init_client()
+        client._listfeed = self._init_listfeed()
+        client._request_response = dict(status=400,
+                                        reason='Data centre explosion')
+        self._init_keyring(client)
+        self.assertRaises(errors.InitError, self.keyring.get_password, 'any', 'thing')
+
+    def test_handles_corrupt_retrieve(self):
+        client = self._init_client()
+        dummy_entries = dict(section1=dict(user1='pwd1'))
+        client._request_response = dict(status=200, data='broken' + self._encode_data(dummy_entries))
+        client._listfeed = self._init_listfeed()
+        self._init_keyring(client)
+        self.assertRaises(errors.InitError, self.keyring.get_password, 'any', 'thing')
+
+    def test_no_create_if_requested(self):
+        client = self._init_client()
+        self.keyring = init_google_docs_keyring(client, can_create=False)
+        self.assertRaises(errors.InitError, self.keyring.get_password, 'any', 'thing')
+
+    def test_no_set_if_create_folder_fails_on_new_keyring(self):
+        import gdata
+        client = self._init_client()
+        client._create_folder_err = gdata.service.RequestError
+        self._init_keyring(client)
+        self.assertEqual(self.keyring.get_password('service-a', 'user-A'), None,
+                        'No password should be set in new keyring')
+        self.assertRaises(errors.PasswordSetError, self.keyring.set_password,
+                          'service-a', 'user-A', 'password-A')
+        self.assertEqual(self.keyring.get_password('service-a', 'user-A'), None,
+                        'No password should be set after write fail')
+
+    def test_no_set_if_write_fails_on_new_keyring(self):
+        import gdata
+        client = self._init_client()
+        client._upload_err = gdata.service.RequestError
+        self._init_keyring(client)
+        self.assertEqual(self.keyring.get_password('service-a', 'user-A'), None,
+                        'No password should be set in new keyring')
+        self.assertRaises(errors.PasswordSetError, self.keyring.set_password,
+                          'service-a', 'user-A', 'password-A')
+        self.assertEqual(self.keyring.get_password('service-a', 'user-A'), None,
+                        'No password should be set after write fail')
+
+    def test_no_set_if_write_fails_on_existing_keyring(self):
+        import gdata
+        client = self._init_client()
+        dummy_entries = dict(sectionB=dict(user9='pwd9'))
+        client._request_response = dict(status=200, data=self._encode_data(dummy_entries))
+        client._put_err = gdata.service.RequestError
+        client._listfeed = self._init_listfeed()
+        self._init_keyring(client)
+        self.assertEqual(self.keyring.get_password('sectionB', 'user9'), 'pwd9',
+                        'Correct password should be set in existing keyring')
+        self.assertRaises(errors.PasswordSetError, self.keyring.set_password,
+                          'sectionB', 'user9', 'Not the same pwd')
+        self.assertEqual(self.keyring.get_password('sectionB', 'user9'), 'pwd9',
+                        'Password should be unchanged after write fail')
+
+    def test_writes_correct_data_to_google_docs(self):
+        client = self._init_client()
+        dummy_entries = dict(sectionWriteChk=dict(userWriteChk='pwd'))
+        client._request_response = dict(status=200, data=self._encode_data(dummy_entries))
+        client._listfeed = self._init_listfeed()
+        self._init_keyring(client)
+        self.keyring.set_password('sectionWriteChk',
+                                  'userWritechk',
+                                  'new_pwd')
+        self.assertIsNotNone(client._put_data, 'Should have written data')
+        self.assertEquals(
+            'new_pwd',
+            client._put_data.get('sectionWriteChk').get('userWritechk'),
+            'Did not write updated password!')
+
+    def test_handles_write_conflict_on_different_service(self):
+        import gdata
+        client = self._init_client()
+        dummy_entries = dict(sectionWriteConflictA=dict(
+            userwriteConflictA='pwdwriteConflictA'))
+        client._request_response = dict(status=200, data=self._encode_data(dummy_entries))
+        client._put_err = [(gdata.service.RequestError,
+                               {'status': '406',
+                                'reason': 'Conflict'}),]
+        client._listfeed = self._init_listfeed()
+        self._init_keyring(client)
+        self.assertEqual(
+            self.keyring.get_password('sectionWriteConflictA',
+                                      'userwriteConflictA'),
+            'pwdwriteConflictA',
+            'Correct password should be set in existing keyring')
+        dummy_entries['diffSection'] = dict(foo='bar')
+        client._request_response = dict(status=200, data=self._encode_data(dummy_entries))
+        new_pwd = 'Not the same pwd'
+        self.keyring.set_password('sectionWriteConflictA',
+                                  'userwriteConflictA',
+                                  new_pwd)
+
+        self.assertEquals(self.keyring.get_password('sectionWriteConflictA',
+                                                    'userwriteConflictA'),
+                          new_pwd
+        )
+        self.assertEqual(1, client._put_count,
+                         'Write not called after conflict resolution')
+
+    def test_handles_write_conflict_on_same_service_and_username(self):
+        import gdata
+        client = self._init_client()
+        dummy_entries = dict(sectionWriteConflictB=dict(
+            userwriteConflictB='pwdwriteConflictB'))
+        client._request_response = dict(status=200, data=self._encode_data(dummy_entries))
+        client._put_err = (gdata.service.RequestError,
+                               {'status': '406',
+                                'reason': 'Conflict'})
+        client._listfeed = self._init_listfeed()
+        self._init_keyring(client)
+        self.assertEqual(
+            self.keyring.get_password('sectionWriteConflictB',
+                                      'userwriteConflictB'),
+            'pwdwriteConflictB',
+            'Correct password should be set in existing keyring')
+        conflicting_dummy_entries = dict(sectionWriteConflictB=dict(
+            userwriteConflictB='pwdwriteConflictC'))
+        client._request_response = dict(status=200, data=self._encode_data(conflicting_dummy_entries))
+        self.assertRaises(errors.PasswordSetError, self.keyring.set_password,
+                          'sectionWriteConflictB', 'userwriteConflictB', 'new_pwd')
+
+    def test_handles_write_conflict_with_identical_change(self):
+        import gdata
+        client = self._init_client()
+        dummy_entries = dict(sectionWriteConflictC=dict(
+            userwriteConflictC='pwdwriteConflictC'))
+        client._request_response = dict(status=200, data=self._encode_data(dummy_entries))
+        client._put_err = [(gdata.service.RequestError,
+                               {'status': '406',
+                                 'reason': 'Conflict'}),]
+        client._listfeed = self._init_listfeed()
+        self._init_keyring(client)
+        self.assertEqual(
+            self.keyring.get_password('sectionWriteConflictC',
+                                      'userwriteConflictC'),
+            'pwdwriteConflictC',
+            'Correct password should be set in existing keyring')
+        new_pwd = 'Not the same pwd'
+        conflicting_dummy_entries = dict(sectionWriteConflictC=dict(
+            userwriteConflictC=new_pwd))
+        client._request_response = dict(status=200, data=self._encode_data(conflicting_dummy_entries))
+        self.keyring.set_password('sectionWriteConflictC',
+                                  'userwriteConflictC',
+                                  new_pwd)
+        self.assertEquals(self.keyring.get_password('sectionWriteConflictC',
+                                                    'userwriteConflictC'),
+                          new_pwd
+        )
+
+    def test_handles_broken_google_put_when_non_owner_update_fails(self):
+        """Google Docs has a bug when putting to a non-owner
+           see  GoogleDocsKeyring._save_keyring()
+        """
+        import gdata
+        client = self._init_client()
+        dummy_entries = dict(sectionBrokenPut=dict(
+            userBrokenPut='pwdBrokenPut'))
+        client._request_response = dict(status=200, data=self._encode_data(dummy_entries))
+        client._put_err = [(
+            gdata.service.RequestError,
+                { 'status': '400',
+                  'body': 'Sorry, there was an error saving the file. Please try again.',
+                  'reason': 'Bad Request'}),]
+        client._listfeed = self._init_listfeed()
+        self._init_keyring(client)
+        new_pwd = 'newPwdBrokenPut'
+        correct_read_entries = dict(sectionBrokenPut=dict(
+            userBrokenPut='pwdBrokenPut'))
+        client._request_response = dict(status=200,
+                                        data=self._encode_data(correct_read_entries))
+        self.assertRaises(errors.PasswordSetError, self.keyring.set_password,
+                          'sectionBrokenPut', 'userBrokenPut', new_pwd)
+
+    def test_handles_broken_google_put_when_non_owner_update(self):
+        """Google Docs has a bug when putting to a non-owner
+           see  GoogleDocsKeyring._save_keyring()
+        """
+        import gdata
+        client = self._init_client()
+        dummy_entries = dict(sectionBrokenPut=dict(
+            userBrokenPut='pwdBrokenPut'))
+        client._request_response = dict(status=200, data=self._encode_data(dummy_entries))
+        client._put_err = [(
+            gdata.service.RequestError,
+                { 'status': '400',
+                  'body': 'Sorry, there was an error saving the file. Please try again.',
+                  'reason': 'Bad Request'}),]
+        client._listfeed = self._init_listfeed()
+        self._init_keyring(client)
+        new_pwd = 'newPwdBrokenPut'
+        correct_read_entries = dict(sectionBrokenPut=dict(
+            userBrokenPut=new_pwd))
+        client._request_response = dict(status=200,
+                                        data=self._encode_data(correct_read_entries))
+        self.keyring.set_password('sectionBrokenPut',
+                                  'userBrokenPut',
+                                  new_pwd)
+        self.assertEquals(self.keyring.get_password('sectionBrokenPut',
+                                                    'userBrokenPut'),
+                          new_pwd)
+
+    def test_uses_existing_folder(self):
+        import gdata
+        client = self._init_client()
+        # should not happen
+        client._create_folder_err = gdata.service.RequestError
+
+        self._init_keyring(client)
+        self.assertEqual(self.keyring.get_password('service-a', 'user-A'), None,
+                         'No password should be set in new keyring')
+        client._listfeed = self._init_listfeed()
+        self.keyring.set_password('service-a', 'user-A', 'password-A')
+        self.assertIsNotNone(client._upload_data, 'Should have written data')
+        self.assertEqual(self.keyring.get_password('service-a', 'user-A'),
+                         'password-A',
+                         'Correct password should be set')
diff --git a/tests/test_Windows.py b/tests/test_Windows.py
new file mode 100644
index 0000000..c93c3e2
--- /dev/null
+++ b/tests/test_Windows.py
@@ -0,0 +1,49 @@
+from __future__ import print_function
+
+import sys
+import unittest
+
+from keyrings.alt import Windows
+from keyring.tests.test_backend import BackendBasicTests
+from .test_file import FileKeyringTests
+
+def is_win32_crypto_supported():
+    try:
+        __import__('keyring.backends._win_crypto')
+    except ImportError:
+        return False
+    return sys.platform in ['win32'] and sys.getwindowsversion()[-2] == 2
+
+def is_winvault_supported():
+    try:
+        __import__('win32cred')
+        has_pywin32 = True
+    except ImportError:
+        has_pywin32 = False
+    return (
+        sys.platform in ['win32'] and sys.getwindowsversion().major >= 6
+        and has_pywin32
+    )
+
+
+ at unittest.skipUnless(is_win32_crypto_supported(),
+                     "Need Windows")
+class Win32CryptoKeyringTestCase(FileKeyringTests, unittest.TestCase):
+
+    def init_keyring(self):
+        return Windows.EncryptedKeyring()
+
+
+ at unittest.skipUnless(Windows.RegistryKeyring.viable
+    and sys.version_info > (3,), "RegistryKeyring not viable")
+class RegistryKeyringTestCase(BackendBasicTests, unittest.TestCase):
+    def tearDown(self):
+        # clean up any credentials created
+        for cred in self.credentials_created:
+            try:
+                self.keyring.delete_password(*cred)
+            except Exception as e:
+                print(e, file=sys.stderr)
+
+    def init_keyring(self):
+        return Windows.RegistryKeyring()
diff --git a/tests/test_crypto.py b/tests/test_crypto.py
new file mode 100644
index 0000000..04dfae0
--- /dev/null
+++ b/tests/test_crypto.py
@@ -0,0 +1,32 @@
+import unittest
+import mock
+
+from .test_file import FileKeyringTests
+
+from keyrings.alt import file
+
+def is_crypto_supported():
+    try:
+        __import__('Crypto.Cipher.AES')
+        __import__('Crypto.Protocol.KDF')
+        __import__('Crypto.Random')
+    except ImportError:
+        return False
+    return True
+
+
+ at unittest.skipUnless(is_crypto_supported(),
+                     "Need Crypto module")
+class CryptedFileKeyringTestCase(FileKeyringTests, unittest.TestCase):
+
+    def setUp(self):
+        super(self.__class__, self).setUp()
+        fake_getpass = mock.Mock(return_value='abcdef')
+        self.patcher = mock.patch('getpass.getpass', fake_getpass)
+        self.patcher.start()
+
+    def tearDown(self):
+        self.patcher.stop()
+
+    def init_keyring(self):
+        return file.EncryptedKeyring()
diff --git a/tests/test_file.py b/tests/test_file.py
new file mode 100644
index 0000000..3037061
--- /dev/null
+++ b/tests/test_file.py
@@ -0,0 +1,52 @@
+import os
+import tempfile
+import sys
+import errno
+import unittest
+
+from keyring.tests.test_backend import BackendBasicTests
+from keyring.tests.util import random_string
+
+from keyrings.alt import file
+
+class FileKeyringTests(BackendBasicTests):
+
+    def setUp(self):
+        super(FileKeyringTests, self).setUp()
+        self.keyring = self.init_keyring()
+        self.keyring.file_path = self.tmp_keyring_file = tempfile.mktemp()
+
+    def tearDown(self):
+        try:
+            os.unlink(self.tmp_keyring_file)
+        except (OSError,):
+            e = sys.exc_info()[1]
+            if e.errno != errno.ENOENT: # No such file or directory
+                raise
+
+    def test_encrypt_decrypt(self):
+        password = random_string(20)
+        # keyring.encrypt expects bytes
+        password = password.encode('utf-8')
+        encrypted = self.keyring.encrypt(password)
+
+        self.assertEqual(password, self.keyring.decrypt(encrypted))
+
+
+class UncryptedFileKeyringTestCase(FileKeyringTests, unittest.TestCase):
+
+    def init_keyring(self):
+        return file.PlaintextKeyring()
+
+    @unittest.skipIf(sys.platform == 'win32',
+        "Group/World permissions aren't meaningful on Windows")
+    def test_keyring_not_created_world_writable(self):
+        """
+        Ensure that when keyring creates the file that it's not overly-
+        permissive.
+        """
+        self.keyring.set_password('system', 'user', 'password')
+
+        self.assertTrue(os.path.exists(self.keyring.file_path))
+        group_other_perms = os.stat(self.keyring.file_path).st_mode & 0o077
+        self.assertEqual(group_other_perms, 0)
diff --git a/tests/test_keyczar.py b/tests/test_keyczar.py
new file mode 100644
index 0000000..d8e1bda
--- /dev/null
+++ b/tests/test_keyczar.py
@@ -0,0 +1,76 @@
+import os
+import unittest
+
+from keyrings.alt import keyczar
+from keyring.tests import mocks
+
+def is_keyczar_supported():
+    return hasattr(keyczar, 'keyczar')
+
+ at unittest.skipUnless(is_keyczar_supported(),
+                     "Need Keyczar")
+class KeyczarCrypterTestCase(unittest.TestCase):
+
+    """Test the keyczar crypter"""
+
+    def setUp(self):
+        self._orig_keyczar = keyczar.keyczar
+        keyczar.keyczar = mocks.MockKeyczar()
+
+    def tearDown(self):
+        keyczar.keyczar = self._orig_keyczar
+        if keyczar.EnvironCrypter.KEYSET_ENV_VAR in os.environ:
+            del os.environ[keyczar.EnvironCrypter.KEYSET_ENV_VAR]
+        if keyczar.EnvironCrypter.ENC_KEYSET_ENV_VAR in os.environ:
+            del os.environ[keyczar.EnvironCrypter.ENC_KEYSET_ENV_VAR]
+
+    def testKeyczarCrypterWithUnencryptedReader(self):
+        """
+        """
+        location = 'bar://baz'
+        kz_crypter = keyczar.Crypter(location)
+        self.assertEquals(location, kz_crypter.keyset_location)
+        self.assertIsNone(kz_crypter.encrypting_keyset_location)
+        self.assertIsInstance(kz_crypter.crypter, mocks.MockKeyczarCrypter)
+        self.assertIsInstance(kz_crypter.crypter.reader, mocks.MockKeyczarReader)
+        self.assertEquals(location, kz_crypter.crypter.reader.location)
+
+    def testKeyczarCrypterWithEncryptedReader(self):
+        """
+        """
+        location = 'foo://baz'
+        encrypting_location = 'castle://aaargh'
+        kz_crypter = keyczar.Crypter(location, encrypting_location)
+        self.assertEquals(location, kz_crypter.keyset_location)
+        self.assertEquals(encrypting_location,
+                          kz_crypter.encrypting_keyset_location)
+        self.assertIsInstance(kz_crypter.crypter, mocks.MockKeyczarCrypter)
+        self.assertIsInstance(kz_crypter.crypter.reader,
+                              mocks.MockKeyczarEncryptedReader)
+        self.assertEquals(location, kz_crypter.crypter.reader._reader.location)
+        self.assertEquals(encrypting_location,
+                          kz_crypter.crypter.reader._crypter.reader.location)
+
+    def testKeyczarCrypterEncryptDecryptHandlesEmptyNone(self):
+        location = 'castle://aargh'
+        kz_crypter = keyczar.Crypter(location)
+        self.assertEquals('', kz_crypter.encrypt(''))
+        self.assertEquals('', kz_crypter.encrypt(None))
+        self.assertEquals('', kz_crypter.decrypt(''))
+        self.assertEquals('', kz_crypter.decrypt(None))
+
+    def testEnvironCrypterReadsCorrectValues(self):
+        location = 'foo://baz'
+        encrypting_location = 'castle://aaargh'
+        kz_crypter = keyczar.EnvironCrypter()
+        os.environ[kz_crypter.KEYSET_ENV_VAR] = location
+        self.assertEqual(location, kz_crypter.keyset_location)
+        self.assertIsNone(kz_crypter.encrypting_keyset_location)
+        os.environ[kz_crypter.ENC_KEYSET_ENV_VAR] = encrypting_location
+        self.assertEqual(encrypting_location, kz_crypter.encrypting_keyset_location)
+
+    def testEnvironCrypterThrowsExceptionOnMissingValues(self):
+        kz_crypter = keyczar.EnvironCrypter()
+        with self.assertRaises(ValueError):
+            kz_crypter.keyset_location
+        self.assertIsNone(kz_crypter.encrypting_keyset_location)
diff --git a/tests/test_kwallet.py b/tests/test_kwallet.py
new file mode 100644
index 0000000..4ab2589
--- /dev/null
+++ b/tests/test_kwallet.py
@@ -0,0 +1,81 @@
+import unittest
+
+from keyrings.alt import kwallet
+from keyring.tests.test_backend import BackendBasicTests
+
+def is_qt4_supported():
+    try:
+        __import__('PyQt4.QtGui')
+    except ImportError:
+        return False
+    return True
+
+ at unittest.skipUnless(kwallet.QtKeyring.viable, "Need KWallet")
+class KDEKWalletTestCase(BackendBasicTests, unittest.TestCase):
+
+    def init_keyring(self):
+        return kwallet.QtKeyring()
+
+
+class UnOpenableKWallet(object):
+    """A module-like object used to test KDE wallet fall-back."""
+
+    Synchronous = None
+
+    def openWallet(self, *args):
+        return None
+
+    def NetworkWallet(self):
+        return None
+
+
+class FauxQtGui(object):
+    """A fake module-like object used in testing the open_kwallet function."""
+
+    class qApp:
+        @staticmethod
+        def instance():
+            pass
+
+    class QApplication(object):
+        def __init__(self, *args):
+            pass
+
+        def exit(self):
+            pass
+
+    class QWidget(object):
+        def __init__(self, *args):
+            pass
+
+        def winId(self):
+            pass
+
+class KDEWalletCanceledTestCase(unittest.TestCase):
+
+    def test_user_canceled(self):
+        # If the user cancels either the "enter your password to unlock the
+        # keyring" dialog or clicks "deny" on the "can this application access
+        # the wallet" dialog then openWallet() will return None.  The
+        # open_wallet() function should handle that eventuality by returning
+        # None to signify that the KWallet backend is not available.
+        self.assertEqual(
+            kwallet.open_kwallet(UnOpenableKWallet(), FauxQtGui()),
+            None)
+
+
+ at unittest.skipUnless(kwallet.QtKeyring.viable and
+                     is_qt4_supported(),
+                     "Need KWallet and Qt4")
+class KDEKWalletInQApplication(unittest.TestCase):
+    def test_QApplication(self):
+        try:
+            from PyKDE4.kdeui import KWallet
+            from PyQt4.QtGui import QApplication
+        except:
+            return
+
+        app = QApplication([])
+        wallet = kwallet.open_kwallet()
+        self.assertIsInstance(wallet, KWallet.Wallet)
+        app.exit()
diff --git a/tests/test_multi.py b/tests/test_multi.py
new file mode 100644
index 0000000..e38fd87
--- /dev/null
+++ b/tests/test_multi.py
@@ -0,0 +1,58 @@
+import unittest
+
+from keyring.backend import KeyringBackend
+from keyrings.alt import multi
+import keyring.errors
+
+class MultipartKeyringWrapperTestCase(unittest.TestCase):
+
+    """Test the wrapper that breaks passwords into smaller chunks"""
+
+    class MockKeyring(KeyringBackend):
+
+        priority = 1
+
+        def __init__(self):
+            self.passwords = {}
+
+        def get_password(self, service, username):
+            return self.passwords.get(service+username)
+
+        def set_password(self, service, username, password):
+            self.passwords[service+username] = password
+
+        def delete_password(self, service, username):
+            try:
+                del self.passwords[service+username]
+            except KeyError:
+                raise keyring.errors.PasswordDeleteError('not found')
+
+    def testViablePassThru(self):
+        kr = multi.MultipartKeyringWrapper(self.MockKeyring())
+        self.assertTrue(kr.viable)
+
+    def testMissingPassword(self):
+        wrapped_kr = self.MockKeyring()
+        kr = multi.MultipartKeyringWrapper(wrapped_kr)
+        self.assertIsNone(kr.get_password('s1', 'u1'))
+
+    def testSmallPasswordSetInSinglePart(self):
+        wrapped_kr = self.MockKeyring()
+        kr = multi.MultipartKeyringWrapper(wrapped_kr)
+        kr.set_password('s1', 'u1', 'p1')
+        self.assertEquals(wrapped_kr.passwords, {'s1u1':'p1'})
+        # should be able to read it back
+        self.assertEquals(kr.get_password('s1', 'u1'), 'p1')
+
+    def testLargePasswordSetInMultipleParts(self):
+        wrapped_kr = self.MockKeyring()
+        kr = multi.MultipartKeyringWrapper(wrapped_kr,
+            max_password_size=2)
+        kr.set_password('s2', 'u2', '0123456')
+        self.assertEquals(wrapped_kr.passwords, {'s2u2':'01',
+                                                 's2u2{{part_1}}':'23',
+                                                 's2u2{{part_2}}':'45',
+                                                 "s2u2{{part_3}}":'6'})
+
+        # should be able to read it back
+        self.assertEquals(kr.get_password('s2', 'u2'), '0123456')
diff --git a/tests/test_pyfs.py b/tests/test_pyfs.py
new file mode 100644
index 0000000..361c4d7
--- /dev/null
+++ b/tests/test_pyfs.py
@@ -0,0 +1,136 @@
+from __future__ import unicode_literals
+
+import os
+import tempfile
+import textwrap
+import unittest
+
+import keyring.backend
+from keyrings.alt import pyfs
+from keyring.tests.test_backend import BackendBasicTests, random_string
+
+
+class ReverseCrypter(keyring.backend.Crypter):
+    """Very silly crypter class"""
+
+    def encrypt(self, value):
+        return value[::-1]
+
+    def decrypt(self, value):
+        return value[::-1]
+
+class PyfilesystemKeyringTests(BackendBasicTests):
+    """Base class for Pyfilesystem tests"""
+
+    def setUp(self):
+        super(PyfilesystemKeyringTests, self).setUp()
+        self.keyring = self.init_keyring()
+
+    def tearDown(self):
+        del self.keyring
+
+    def test_encrypt_decrypt(self):
+        password = random_string(20)
+        encrypted = self.keyring.encrypt(password)
+
+        self.assertEqual(password, self.keyring.decrypt(encrypted))
+
+
+ at unittest.skipUnless(pyfs.BasicKeyring.viable, "Need Pyfilesystem")
+class UnencryptedMemoryPyfilesystemKeyringNoSubDirTestCase(
+        PyfilesystemKeyringTests, unittest.TestCase):
+    """Test in memory with no encryption"""
+
+    keyring_filename = 'mem://unencrypted'
+
+    def init_keyring(self):
+        return keyring.backends.pyfs.PlaintextKeyring(
+            filename=self.keyring_filename)
+
+
+ at unittest.skipUnless(pyfs.BasicKeyring.viable, "Need Pyfilesystem")
+class UnencryptedMemoryPyfilesystemKeyringSubDirTestCase(
+        PyfilesystemKeyringTests, unittest.TestCase):
+    """Test in memory with no encryption"""
+
+    keyring_filename = 'mem://some/sub/dir/unencrypted'
+
+    def init_keyring(self):
+        return keyring.backends.pyfs.PlaintextKeyring(
+            filename=self.keyring_filename)
+
+
+ at unittest.skipUnless(pyfs.BasicKeyring.viable, "Need Pyfilesystem")
+class UnencryptedLocalPyfilesystemKeyringNoSubDirTestCase(
+        PyfilesystemKeyringTests, unittest.TestCase):
+    """Test using local temp files with no encryption"""
+
+    keyring_filename = '%s/keyring.cfg' %tempfile.mkdtemp()
+
+    def init_keyring(self):
+        return keyring.backends.pyfs.PlaintextKeyring(
+            filename=self.keyring_filename)
+
+    def test_handles_preexisting_keyring(self):
+        from fs.opener import opener
+        fs, path = opener.parse(self.keyring_filename, writeable=True)
+        keyring_file = fs.open(path, 'w')
+        file_data = textwrap.dedent("""
+            [svc1]
+            user1 = cHdkMQ==
+            """).lstrip()
+        keyring_file.write(file_data)
+        keyring_file.close()
+        pyf_keyring = keyring.backends.pyfs.PlaintextKeyring(
+            filename=self.keyring_filename)
+        self.assertEquals('pwd1', pyf_keyring.get_password('svc1', 'user1'))
+
+    def tearDown(self):
+        del self.keyring
+        if os.path.exists(self.keyring_filename):
+            os.remove(self.keyring_filename)
+
+ at unittest.skipUnless(pyfs.BasicKeyring.viable, "Need Pyfilesystem")
+class UnencryptedLocalPyfilesystemKeyringSubDirTestCase(
+        PyfilesystemKeyringTests, unittest.TestCase):
+    """Test using local temp files with no encryption"""
+
+    keyring_dir = os.path.join(tempfile.mkdtemp(), 'more', 'sub', 'dirs')
+    keyring_filename = os.path.join(keyring_dir, 'keyring.cfg')
+
+    def init_keyring(self):
+
+        if not os.path.exists(self.keyring_dir):
+            os.makedirs(self.keyring_dir)
+        return keyring.backends.pyfs.PlaintextKeyring(
+            filename=self.keyring_filename)
+
+ at unittest.skipUnless(pyfs.BasicKeyring.viable, "Need Pyfilesystem")
+class EncryptedMemoryPyfilesystemKeyringTestCase(PyfilesystemKeyringTests,
+        unittest.TestCase):
+    """Test in memory with encryption"""
+
+    def init_keyring(self):
+        return keyring.backends.pyfs.EncryptedKeyring(
+            ReverseCrypter(),
+            filename='mem://encrypted/keyring.cfg')
+
+ at unittest.skipUnless(pyfs.BasicKeyring.viable, "Need Pyfilesystem")
+class EncryptedLocalPyfilesystemKeyringNoSubDirTestCase(
+        PyfilesystemKeyringTests, unittest.TestCase):
+    """Test using local temp files with encryption"""
+
+    def init_keyring(self):
+        return keyring.backends.pyfs.EncryptedKeyring(
+            ReverseCrypter(),
+            filename='temp://keyring.cfg')
+
+ at unittest.skipUnless(pyfs.BasicKeyring.viable, "Need Pyfilesystem")
+class EncryptedLocalPyfilesystemKeyringSubDirTestCase(
+        PyfilesystemKeyringTests, unittest.TestCase):
+    """Test using local temp files with encryption"""
+
+    def init_keyring(self):
+        return keyring.backends.pyfs.EncryptedKeyring(
+            ReverseCrypter(),
+            filename='temp://a/sub/dir/hierarchy/keyring.cfg')

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



More information about the Python-modules-commits mailing list