Skip to content

Instantly share code, notes, and snippets.

@cam-stitt
Created February 24, 2014 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cam-stitt/9182568 to your computer and use it in GitHub Desktop.
Save cam-stitt/9182568 to your computer and use it in GitHub Desktop.
A SQLAlchemy field to process "tags"
from unittest import TestCase
from sqlalchemy.types import TypeDecorator, VARCHAR
class Tags(TypeDecorator):
impl = VARCHAR
def process_bind_param(self, value, dialect):
if value is None:
return None
return ",".join(value)
def process_result_value(self, value, dialect):
if value is None:
return None
return value.split(",")
class FieldTests(TestCase):
def setUp(self):
self.tags = Tags()
self.value = ["hi", "there"]
self.expected_response = "hi,there"
def test_set_none_returns_none(self):
val = self.tags.process_bind_param(None, "")
self.assertEqual(val, None)
def test_set_list_returns_string(self):
val = self.tags.process_bind_param(self.value, "")
self.assertEqual(val, self.expected_response)
def test_list_not_string_raises_type_error(self):
with self.assertRaises(TypeError):
self.tags.process_bind_param([1, 2, 3], "")
def test_get_none_returns_none(self):
val = self.tags.process_result_value(None, "")
self.assertEqual(val, None)
def test_get_string_returns_list(self):
val = self.tags.process_result_value(self.expected_response, "")
self.assertEqual(val, self.value)
def test_get_not_string_raises_attribute_error(self):
with self.assertRaises(AttributeError):
self.tags.process_result_value(4, "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment