class TestRead(unittest.TestCase):
    def setUp(self):
        self.mitzi = identity('mitzi')
        self.cache = IdentityCache()
        self.rr    = ReadRequest(self.mitzi)

        self.cache.update_ident(self.mitzi)

    def test_serialize_eq_self(self):
        # No change between runs
        self.assertEqual(
            self.rr.serialize(),
            self.rr.serialize()
        )

    def test_serialize_keys(self):
        serialized = self.rr.serialize()
        self.assertEqual(
            sorted(serialized.keys()),
            ['author', 'type', 'unique']
        )

    def test_serialize_cycle(self):
        serialized = self.rr.serialize()
        rr2 = Action(serialized, self.cache).specific()
        self.assertEqual(serialized, rr2.serialize())
 def test_sync(self):
     mitzi_cache = IdentityCache()
     atlas_cache = IdentityCache()
     mitzi_cache.update_ident(self.mitzi_ident)
     atlas_cache.update_ident(self.atlas_ident)
     mitzi_cache.sync(atlas_cache)
     self._assert_caches(mitzi_cache, atlas_cache)
class TestIdentityRef(unittest.TestCase):
    def setUp(self):
        self.ident = mockup()
        self.cache = IdentityCache()
        self.cache.update_ident(self.ident)
        self.ref = IdentRef(self.ident.key, self.cache)

    def thorough_equality(self, other_ref):
        self.assertEqual(self.ref, other_ref)
        self.assertEqual(hash(self.ref), hash(other_ref))

    def thorough_inequality(self, ineq_ref):
        self.assertNotEqual(self.ref, ineq_ref)
        self.assertNotEqual(hash(self.ref), hash(ineq_ref))

    def test_eq(self):
        self.thorough_equality(IdentRef(self.ident.key, self.cache))
        self.thorough_inequality(IdentRef("random key", self.cache))
        self.thorough_inequality(IdentRef(self.ident.key, IdentityCache()))

    def test_deref(self):
        self.assertEqual(self.ident, self.ref.deref())

    def test_from_cache(self):
        self.assertEqual(self.ref, self.cache.ref(self.ident))
        self.assertEqual(self.ref, self.cache.ref(self.ident.key))

    def test_from_ident(self):
        self.assertEqual(self.ref, self.ident.ref(self.cache))

    def test_hashable(self):
        # What can I say, I'm paranoid.
        myset = set([self.ref])
        self.assertIn(self.ref, myset)
        self.assertEquals(list(myset), [self.ref])
    def test_deserialize(self):
        self.cache.update_ident(self.mitzi_ident)
        self.cache.update_ident(self.atlas_ident)

        serialization = self.cache.serialize()
        new_cache = IdentityCache()
        new_cache.deserialize(serialization)
        self._assert_caches(self.cache, new_cache)
    def get_ident(self, name):
        cache = IdentityCache()
        cache.update_idents(self.source.get_user(name))

        if len(cache.all()) > 0:
            status = 200
        else:
            status = 404

        payload = json.dumps(cache.serialize())
        if bytes != str:
            payload = bytes(payload, 'utf-8')
        return self.result(status, 'application/json', payload)
 def test_decode(self):
     from ejtp.identity import Identity, IdentityCache
     cache = IdentityCache()
     cache[['testing']] = Identity('joe', ['rotate', 1], ['testing'])
     self.assertEqual(
         frame.encrypted.EncryptedFrame('r["testing"]\x00gpp').decode(
             cache), RawData('foo'))
 def test_decode(self):
     from ejtp.identity import Identity, IdentityCache
     ident = Identity('joe', ['rotate', 1], ['testing'])
     cache = IdentityCache()
     cache[['testing']] = ident
     signature = ident.sign('foo')
     siglen = len(signature)
     signed_content = RawData('s["testing"]\x00') + (
         siglen // 256, siglen % 256) + signature + 'foo'
     self.assertEqual(
         frame.signed.SignedFrame(signed_content).decode(cache),
         RawData('foo'))
     self.assertRaises(
         ValueError,
         frame.signed.SignedFrame(
             's["testing"]\x00\x00\x07invalidfoo').decode, cache)
Example #8
0
    def get_ident(self, name):
        cache = IdentityCache()
        cache.update_idents(self.source.get_user(name))

        if len(cache.all()) > 0:
            status = 200
        else:
            status = 404

        payload = json.dumps(cache.serialize())
        if bytes != str:
            payload = bytes(payload, 'utf-8')
        return self.result(status, 'application/json', payload)
    def setUp(self):
        self.mitzi = identity('mitzi')
        self.cache = IdentityCache()
        self.rr    = ReadRequest(self.mitzi)

        self.cache.update_ident(self.mitzi)
Example #10
0
    def do_dinit(self, args):
        '''
        Initialize DEJE interactivity.

        This command must be used before any of the other d*
        commands. It reads from a few of the values in variable
        storage as initialization parameters:

        * idcache - EJTP identity cache
        * identity - location of EJTP identity in cache
        * docname - Name of the document for network sync
        * docserialized - serialized version of document

        The dinit command can be run more than once, but it's
        a bit of a reset, and may cause data loss in the
        stateful parts of the protocol. But it's also the only
        way to update the parameters used by the DEJE code -
        for example, any changes to the 'idcache' variable after
        initialization will have no effect.
        '''
        try:
            params = self.get_vars(
                'idcache',
                'identity',
                'docname',
                'docserialized'
            )
        except KeyError as e:
            self.fail('Need to set variable %r' % e.args[0])
        
        cache = IdentityCache()
        try:
            cache.deserialize(params['idcache'])
        except:
            self.fail('Could not deserialize data in idcache')

        try:
            ident = cache.find_by_location(params['identity'])
        except KeyError:
            loc_string = strict(params['identity']).export()
            self.fail('No identity in cache for ' + loc_string)

        owner = Owner(ident)
        owner.identities = cache
        owner.client.rcv_callback = self.on_ejtp

        self.write_json = owner.client.write_json
        owner.client.write_json = self.write_json_wrapped

        if type(params['docname']) != str:
            json_str = strict(params['docname']).export()
            self.fail('Not a valid docname: ' + json_str)

        doc = Document(params['docname'], owner=owner)

        try:
            doc.deserialize(params['docserialized'])
        except Exception as e:
            self.fail('Failed to deserialize data:\n%r' % e)

        doc.signals['enact-event'].connect(self.on_event)
        doc.debug = self.debug

        # Wait until everything that could fail has gone right
        self.interface.owner = owner
        self.interface.document = doc
        self.output('DEJE initialized')
 def test_eq(self):
     self.thorough_equality(IdentRef(self.ident.key, self.cache))
     self.thorough_inequality(IdentRef("random key", self.cache))
     self.thorough_inequality(IdentRef(self.ident.key, IdentityCache()))
 def setUp(self):
     self.ident = mockup()
     self.cache = IdentityCache()
     self.cache.update_ident(self.ident)
     self.ref = IdentRef(self.ident.key, self.cache)
 def setUp(self):
     self.cache = IdentityCache()
     self.joe_ident = Identity('joe', ['rotate', 3], ['local', None, 'joe'])
     self.mitzi_ident = mockup('mitzi')
     self.atlas_ident = mockup('atlas')
     self.victor_ident = mockup('victor')
class TestIdentityCache(unittest.TestCase):
    def setUp(self):
        self.cache = IdentityCache()
        self.joe_ident = Identity('joe', ['rotate', 3], ['local', None, 'joe'])
        self.mitzi_ident = mockup('mitzi')
        self.atlas_ident = mockup('atlas')
        self.victor_ident = mockup('victor')

    def test_setitem_wrong_type(self):
        self.assertRaisesRegexp(TypeError,
                                "Expected ejtp.identity.core.Identity",
                                self.cache.__setitem__, self.joe_ident, [])

    def test_setitem_wrong_location(self):
        self.assertRaisesRegexp(ValueError,
                                "Trying to cache ident in the wrong location",
                                self.cache.__setitem__, ['x', 'y', 'z'],
                                self.joe_ident)

    def test_update_idents(self):
        idents = [self.joe_ident, self.victor_ident]
        self.cache.update_idents(idents)
        self.assertEquals(sorted(self.cache.all(), key=lambda x: x.key),
                          sorted(idents, key=lambda x: x.key))
        for i in idents:
            self.assertEquals(self.cache[i.location], i)

    def test_filter_by_name(self):
        # Create alternate-universe Joe
        alt_joe = self.joe_ident.clone()
        alt_joe.location = ['local', None, 'alt_joe']

        idents = [self.mitzi_ident, self.joe_ident, alt_joe]
        self.cache.update_idents(idents)

        self.assertEqual(self.cache.filter_by_name(self.mitzi_ident.name),
                         [self.mitzi_ident])

        joe_filtered = self.cache.filter_by_name(self.joe_ident.name)
        self.assertEqual(
            sorted(joe_filtered, key=lambda x: x.key),
            sorted([self.joe_ident, alt_joe], key=lambda x: x.key))

    def test_serialize(self):
        self.cache.update_ident(self.mitzi_ident)
        serialized_ident = self.cache.serialize()
        self.assertIn('["local",null,"mitzi"]', serialized_ident)

    def test_encrypt_capable(self):
        self.cache.update_ident(self.mitzi_ident)
        self.cache.update_ident(self.atlas_ident.public())
        self.cache.update_ident(self.joe_ident)

        capable = [ident.name for ident in self.cache.encrypt_capable()]
        self.assertIn('joe', capable)
        self.assertIn('*****@*****.**', capable)
        self.assertNotIn('*****@*****.**', capable)

    def _assert_caches(self, cache1, cache2):
        for item in zip(sorted(cache1.cache.keys()),
                        sorted(cache2.cache.keys())):
            self.assertEqual(*item)

    def test_sync(self):
        mitzi_cache = IdentityCache()
        atlas_cache = IdentityCache()
        mitzi_cache.update_ident(self.mitzi_ident)
        atlas_cache.update_ident(self.atlas_ident)
        mitzi_cache.sync(atlas_cache)
        self._assert_caches(mitzi_cache, atlas_cache)

    def test_deserialize(self):
        self.cache.update_ident(self.mitzi_ident)
        self.cache.update_ident(self.atlas_ident)

        serialization = self.cache.serialize()
        new_cache = IdentityCache()
        new_cache.deserialize(serialization)
        self._assert_caches(self.cache, new_cache)

    def test_load_from_without_args(self):
        self.assertRaisesRegexp(
            ValueError, 'Must provide either file_path or file_object',
            self.cache.load_from)

    def test_load(self):
        self.cache.load_from(testing_path('examplecache.json'))
        atlas_location = self.cache.find_by_name(
            "*****@*****.**").location
        self.assertListEqual(self.atlas_ident.location, atlas_location)

    def test_save_to_without_args(self):
        self.assertRaisesRegexp(
            ValueError, 'Must provide either file_path or file_object',
            self.cache.save_to)

    def test_save_to(self):
        filename = 'temp.json'
        self.cache.update_ident(self.mitzi_ident)
        self.cache.save_to(filename, indent=4)
        os.remove(filename)