1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
|
import pytest
from datetime import timezone
from decimal import Decimal
from datetime import date, timedelta, datetime, time
from django.test import override_settings
from django.template import defaultfilters
from dynamic_preferences import serializers
from .test_app.models import BlogEntry, BlogEntryWithNonIntPk
@pytest.fixture
def blog_entries(db):
BlogEntry.objects.bulk_create(
[
BlogEntry(title="This is a test", content="Hello World"),
BlogEntry(title="This is only a test", content="Hello World"),
]
)
BlogEntryWithNonIntPk.objects.bulk_create(
[
BlogEntryWithNonIntPk(title="This is a test", content="Hello World"),
BlogEntryWithNonIntPk(title="This is only a test", content="Hello World"),
]
)
def test_boolean_serialization():
s = serializers.BooleanSerializer
assert s.serialize(True) == "True"
assert s.serialize(False) == "False"
with pytest.raises(s.exception):
s.serialize("yolo")
def test_boolean_deserialization():
s = serializers.BooleanSerializer
for v in s.true:
assert s.deserialize(v) is True
for v in s.false:
assert s.deserialize(v) is False
with pytest.raises(s.exception):
s.deserialize("I'm a true value")
def test_int_serialization():
s = serializers.IntSerializer
assert s.serialize(1) == "1"
assert s.serialize(666) == "666"
assert s.serialize(-144) == "-144"
assert s.serialize(0) == "0"
assert s.serialize(123456) == "123456"
with pytest.raises(s.exception):
s.serialize("I'm an integer")
def test_decimal_serialization():
s = serializers.DecimalSerializer
assert s.serialize(Decimal("1")) == "1"
assert s.serialize(Decimal("-1")) == "-1"
assert s.serialize(Decimal("-666.6")) == "-666.6"
assert s.serialize(Decimal("666.6")) == "666.6"
with pytest.raises(s.exception):
s.serialize("I'm a decimal")
def test_float_serialization():
s = serializers.FloatSerializer
assert s.serialize(1.0) == "1.0"
assert s.serialize(-1.0) == "-1.0"
assert s.serialize(1) == "1.0"
assert s.serialize(-1) == "-1.0"
assert s.serialize(-666.6) == "-666.6"
assert s.serialize(666.6) == "666.6"
with pytest.raises(s.exception):
s.serialize("I'm a float")
def test_float_deserialization():
s = serializers.FloatSerializer
assert s.deserialize("1.0") == float("1.0")
assert s.deserialize("-1.0") == float("-1.0")
assert s.deserialize("-666.6") == float("-666.6")
assert s.deserialize("666.6") == float("666.6")
with pytest.raises(s.exception):
s.serialize("I'm a float")
def test_int_deserialization():
s = serializers.DecimalSerializer
assert s.deserialize("1") == Decimal("1")
assert s.deserialize("-1") == Decimal("-1")
assert s.deserialize("-666.6") == Decimal("-666.6")
assert s.deserialize("666.6") == Decimal("666.6")
with pytest.raises(s.exception):
s.serialize("I'm a decimal!")
def test_string_serialization():
s = serializers.StringSerializer
assert s.serialize("Bonjour") == "Bonjour"
assert s.serialize("12") == "12"
assert (
s.serialize("I'm a long sentence, but I rock")
== "I'm a long sentence, but I rock"
)
# check for HTML escaping
kwargs = {
"escape_html": True,
}
assert s.serialize(
"<span>Please, I don't wanna disappear</span>", **kwargs
) == defaultfilters.force_escape("<span>Please, I don't wanna disappear</span>")
with pytest.raises(s.exception):
s.serialize(("I", "Want", "To", "Be", "A", "String"))
def test_string_deserialization():
s = serializers.StringSerializer
assert s.deserialize("Bonjour") == "Bonjour"
assert s.deserialize("12") == "12"
assert (
s.deserialize("I'm a long sentence, but I rock")
== "I'm a long sentence, but I rock"
)
# check case where empty string (value can be None)
assert s.deserialize(None) == ""
assert s.deserialize("") == ""
kwargs = {
"escape_html": True,
}
assert s.deserialize(
s.serialize("<span>Please, I don't wanna disappear</span>", **kwargs)
) == defaultfilters.force_escape("<span>Please, I don't wanna disappear</span>")
def test_duration_serialization():
s = serializers.DurationSerializer
assert s.serialize(timedelta(minutes=1)) == "00:01:00"
assert s.serialize(timedelta(milliseconds=1)) == "00:00:00.001000"
assert s.serialize(timedelta(weeks=1)) == "7 00:00:00"
with pytest.raises(s.exception):
s.serialize("Not a timedelta")
def test_duration_deserialization():
s = serializers.DurationSerializer
assert s.deserialize("7 00:00:00") == timedelta(weeks=1)
with pytest.raises(s.exception):
s.deserialize("Invalid duration string")
def test_date_serialization():
s = serializers.DateSerializer
assert s.serialize(date(2017, 10, 5)) == "2017-10-05"
with pytest.raises(s.exception):
s.serialize("Not a date")
def test_date_deserialization():
s = serializers.DateSerializer
assert s.deserialize("1900-01-01") == date(1900, 1, 1)
with pytest.raises(s.exception):
s.deserialize("Invalid date string")
def test_datetime_serialization():
s = serializers.DateTimeSerializer
# If TZ is enabled default timezone is America/Chicago
# https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-TIME_ZONE
assert (
s.serialize(datetime(2017, 10, 5, 23, 45, 1, 792346))
== "2017-10-05T23:45:01.792346-05:00"
)
with override_settings(USE_TZ=False):
assert s.serialize(
datetime(2017, 10, 5, 23, 45, 1, 792346)
), "2017-10-05T23:45:01.792346"
with pytest.raises(s.exception) as ex:
s.serialize("a string")
assert ex.exception.args == (
"Cannot serialize, value 'a string' is not a datetime object",
)
def test_datetime_deserialization():
s = serializers.DateTimeSerializer
assert s.deserialize("2017-10-05T23:45:01.792346") == datetime(
2017, 10, 5, 23, 45, 1, 792346
)
assert s.deserialize("2017-10-05T23:45:01.792346+00:00") == datetime(
2017, 10, 5, 23, 45, 1, 792346, tzinfo=timezone.utc
)
with pytest.raises(s.exception) as ex:
s.deserialize("abcd")
assert ex.exception.args == (
"Value abcd cannot be converted to a datetime object",
)
def test_time_serialization():
s = serializers.TimeSerializer
assert s.serialize(time(hour=5)) == "05:00:00"
assert s.serialize(time(minute=30)) == "00:30:00"
assert s.serialize(time(23, 59, 59, 999999)) == "23:59:59.999999"
with pytest.raises(s.exception):
s.serialize("Not a time")
def test_time_deserialization():
s = serializers.TimeSerializer
assert s.deserialize("23:00:00") == time(hour=23)
with pytest.raises(s.exception):
s.deserialize("Invalid time string")
def test_multiple_serialization():
s = serializers.MultipleSerializer
assert s.serialize(["a", "b", "c"]) == "a,b,c"
assert (
s.serialize(["key,with,comma", "b", "another,key,with,comma"])
== "another,,key,,with,,comma,b,key,,with,,comma"
)
with pytest.raises(s.exception):
s.serialize(["a", "", "c"])
def test_multiple_deserialization():
s = serializers.MultipleSerializer
assert s.deserialize("a,b,c") == ["a", "b", "c"]
assert s.deserialize("key,,with,,comma,b,another,,key,,with,,comma") == [
"key,with,comma",
"b",
"another,key,with,comma",
]
def test_model_multiple_serialization(blog_entries):
s = serializers.ModelMultipleSerializer(BlogEntry)
blog_entries = BlogEntry.objects.all()
assert s.serialize(blog_entries), s.separator.join(
map(str, sorted(list(blog_entries.values_list("pk", flat=True))))
)
def test_model_multiple_deserialization(blog_entries):
s = serializers.ModelMultipleSerializer(BlogEntry)
blog_entries = BlogEntry.objects.all()
pks = s.separator.join(
map(str, sorted(list(blog_entries.values_list("pk", flat=True))))
)
assert list(s.deserialize(pks)) == list(blog_entries)
def test_model_multiple_single_serialization(blog_entries):
s = serializers.ModelMultipleSerializer(BlogEntry)
blog_entry = BlogEntry.objects.all().first()
assert s.serialize(blog_entry) == s.separator.join(map(str, [blog_entry.pk]))
def test_model_multiple_serialization_with_non_int_pk(blog_entries):
s = serializers.ModelMultipleSerializer(BlogEntryWithNonIntPk)
blog_entries = BlogEntryWithNonIntPk.objects.all()
assert s.serialize(blog_entries) == s.separator.join(
map(str, sorted(list(blog_entries.values_list("pk", flat=True))))
)
def test_model_multiple_deserialization_with_non_int_pk(blog_entries):
s = serializers.ModelMultipleSerializer(BlogEntryWithNonIntPk)
blog_entries = BlogEntryWithNonIntPk.objects.all()
pks = s.separator.join(
map(str, sorted(list(blog_entries.values_list("pk", flat=True))))
)
deserialized_ids = sorted([instance.pk for instance in s.deserialize(pks)])
blog_entries_ids = sorted([entry.pk for entry in blog_entries])
assert deserialized_ids, blog_entries_ids
def test_model_multiple_single_serialization_with_non_int_pk(blog_entries):
s = serializers.ModelMultipleSerializer(BlogEntryWithNonIntPk)
blog_entry = BlogEntryWithNonIntPk.objects.all().first()
assert s.serialize(blog_entry) == s.separator.join(map(str, [blog_entry.pk]))
def test_model_multiple_to_db_empty(blog_entries):
result = serializers.ModelMultipleSerializer(BlogEntry).to_db([])
assert result is None
def test_model_multiple_to_db_multiple(blog_entries):
entry1 = BlogEntry.objects.get(title="This is a test",)
entry2 = BlogEntry.objects.get(title="This is only a test",)
result = serializers.ModelMultipleSerializer(BlogEntry).to_db([
entry1,
entry2,
])
assert result == f'{entry1.pk},{entry2.pk}'
def test_model_multiple_to_db_invalid(blog_entries):
with pytest.raises(ValueError, match=r"Cannot handle value.* of type .*"):
serializers.ModelMultipleSerializer(BlogEntry).to_db('invalid')
|