mirror of https://github.com/peter4431/rq.git
Implement Customizable Serializer Support (#1219)
* Implement Customizable Serializer Support * Refractor serializer instance methods * Update tests with other serializers * Edit function description * Edit function description * Raise appropriate exception * Update tests for better code coverage * Remove un-used imports and un-necessary code * Refractor resolve_serializer * Remove un-necessary alias from imports * Add documentation * Refractor tests, improve documentationmain
parent
d914343e7c
commit
e1cbc3736c
@ -0,0 +1,25 @@
|
||||
import pickle
|
||||
|
||||
from .compat import string_types
|
||||
from .utils import import_attribute
|
||||
|
||||
|
||||
def resolve_serializer(serializer):
|
||||
"""This function checks the user defined serializer for ('dumps', 'loads') methods
|
||||
It returns a default pickle serializer if not found else it returns a MySerializer
|
||||
The returned serializer objects implement ('dumps', 'loads') methods
|
||||
Also accepts a string path to serializer that will be loaded as the serializer
|
||||
"""
|
||||
if not serializer:
|
||||
return pickle
|
||||
|
||||
if isinstance(serializer, string_types):
|
||||
serializer = import_attribute(serializer)
|
||||
|
||||
default_serializer_methods = ('dumps', 'loads')
|
||||
|
||||
for instance_method in default_serializer_methods:
|
||||
if not hasattr(serializer, instance_method):
|
||||
raise NotImplementedError('Serializer should have (dumps, loads) methods.')
|
||||
|
||||
return serializer
|
@ -0,0 +1,37 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import (absolute_import, division, print_function,
|
||||
unicode_literals)
|
||||
|
||||
import json
|
||||
import pickle
|
||||
import queue
|
||||
import unittest
|
||||
|
||||
from rq.serializers import resolve_serializer
|
||||
|
||||
|
||||
class TestSerializers(unittest.TestCase):
|
||||
def test_resolve_serializer(self):
|
||||
"""Ensure function resolve_serializer works correctly"""
|
||||
serializer = resolve_serializer(None)
|
||||
self.assertIsNotNone(serializer)
|
||||
self.assertEqual(serializer, pickle)
|
||||
|
||||
# Test using json serializer
|
||||
serializer = resolve_serializer(json)
|
||||
self.assertIsNotNone(serializer)
|
||||
|
||||
self.assertTrue(hasattr(serializer, 'dumps'))
|
||||
self.assertTrue(hasattr(serializer, 'loads'))
|
||||
|
||||
# Test raise NotImplmentedError
|
||||
with self.assertRaises(NotImplementedError):
|
||||
resolve_serializer(object)
|
||||
|
||||
# Test raise Exception
|
||||
with self.assertRaises(Exception):
|
||||
resolve_serializer(queue.Queue())
|
||||
|
||||
# Test using path.to.serializer string
|
||||
serializer = resolve_serializer('tests.fixtures.Serializer')
|
||||
self.assertIsNotNone(serializer)
|
Loading…
Reference in New Issue