def testCustomEncoderDecoderShouldSucceed(self): "Test a custom encoder and decoder" class CustomClass(object): key = '' val = '' def __init__(self, k='', v=''): self.key = k self.val = v class TestEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, CustomClass): return 'CustomClass:{}:{}'.format(obj.key, obj.val) return json.JSONEncoder.encode(self, obj) class TestDecoder(json.JSONDecoder): def decode(self, obj): d = json.JSONDecoder.decode(self, obj) if isinstance(d, six.string_types) and \ d.startswith('CustomClass:'): s = d.split(':') return CustomClass(k=s[1], v=s[2]) return d rj = Client(encoder=TestEncoder(), decoder=TestDecoder(), port=port, decode_responses=True) rj.flushdb() # Check a regular string self.assertTrue(rj.jsonset('foo', Path.rootPath(), 'bar')) self.assertEqual('string', rj.jsontype('foo', Path.rootPath())) self.assertEqual('bar', rj.jsonget('foo', Path.rootPath())) # Check the custom encoder self.assertTrue( rj.jsonset('cus', Path.rootPath(), CustomClass('foo', 'bar'))) # Check the custom decoder obj = rj.jsonget('cus', Path.rootPath()) self.assertIsNotNone(obj) self.assertEqual(CustomClass, obj.__class__) self.assertEqual('foo', obj.key) self.assertEqual('bar', obj.val) # Test resetting the decoder after the client have been created rj.setDecoder(json.JSONDecoder()) obj = rj.jsonget('cus', Path.rootPath()) self.assertIsNotNone(obj) self.assertNotEqual(CustomClass, obj.__class__) # Test setting the decoder after the client have been created rj.setDecoder(TestDecoder()) obj = rj.jsonget('cus', Path.rootPath()) self.assertIsNotNone(obj) self.assertEqual(CustomClass, obj.__class__) self.assertEqual('foo', obj.key) self.assertEqual('bar', obj.val)
class Database: """Database handler""" def __init__(self, database_name, port=6379): self.database = Client(host=database_name, port=port, decode_responses=True) def flush(self): """Flushing a certain table of the database""" return self.database.flushdb() def import_data(self, keyname, data): """Load data into the database""" return self.database.jsonset(keyname, Path.rootPath(), data) def ping(self): """Tests the connection""" return self.database.ping()
def setUp(self): global rj rj = Client(port=port, decode_responses=True) rj.flushdb()
def rejson(): # TODO: Port from env, etc. r = JsonClient(decode_responses=True, port=6380) yield r r.flushdb()