test_json.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import datetime
  4. import decimal
  5. import json
  6. import re
  7. from django.core import serializers
  8. from django.core.serializers.base import DeserializationError
  9. from django.core.serializers.json import DjangoJSONEncoder
  10. from django.db import models
  11. from django.test import SimpleTestCase, TestCase, TransactionTestCase
  12. from django.test.utils import isolate_apps
  13. from django.utils.translation import override, ugettext_lazy
  14. from .models import Score
  15. from .tests import SerializersTestBase, SerializersTransactionTestBase
  16. class JsonSerializerTestCase(SerializersTestBase, TestCase):
  17. serializer_name = "json"
  18. pkless_str = """[
  19. {
  20. "pk": null,
  21. "model": "serializers.category",
  22. "fields": {"name": "Reference"}
  23. }, {
  24. "model": "serializers.category",
  25. "fields": {"name": "Non-fiction"}
  26. }]"""
  27. mapping_ordering_str = """[
  28. {
  29. "model": "serializers.article",
  30. "pk": %(article_pk)s,
  31. "fields": {
  32. "author": %(author_pk)s,
  33. "headline": "Poker has no place on ESPN",
  34. "pub_date": "2006-06-16T11:00:00",
  35. "categories": [
  36. %(first_category_pk)s,
  37. %(second_category_pk)s
  38. ],
  39. "meta_data": []
  40. }
  41. }
  42. ]
  43. """
  44. @staticmethod
  45. def _validate_output(serial_str):
  46. try:
  47. json.loads(serial_str)
  48. except Exception:
  49. return False
  50. else:
  51. return True
  52. @staticmethod
  53. def _get_pk_values(serial_str):
  54. ret_list = []
  55. serial_list = json.loads(serial_str)
  56. for obj_dict in serial_list:
  57. ret_list.append(obj_dict["pk"])
  58. return ret_list
  59. @staticmethod
  60. def _get_field_values(serial_str, field_name):
  61. ret_list = []
  62. serial_list = json.loads(serial_str)
  63. for obj_dict in serial_list:
  64. if field_name in obj_dict["fields"]:
  65. ret_list.append(obj_dict["fields"][field_name])
  66. return ret_list
  67. def test_indentation_whitespace(self):
  68. s = serializers.json.Serializer()
  69. json_data = s.serialize([Score(score=5.0), Score(score=6.0)], indent=2)
  70. for line in json_data.splitlines():
  71. if re.search(r'.+,\s*$', line):
  72. self.assertEqual(line, line.rstrip())
  73. @isolate_apps('serializers')
  74. def test_custom_encoder(self):
  75. class ScoreDecimal(models.Model):
  76. score = models.DecimalField()
  77. class CustomJSONEncoder(json.JSONEncoder):
  78. def default(self, o):
  79. if isinstance(o, decimal.Decimal):
  80. return str(o)
  81. return super(CustomJSONEncoder, self).default(o)
  82. s = serializers.json.Serializer()
  83. json_data = s.serialize(
  84. [ScoreDecimal(score=decimal.Decimal(1.0))], cls=CustomJSONEncoder
  85. )
  86. self.assertIn('"fields": {"score": "1"}', json_data)
  87. def test_json_deserializer_exception(self):
  88. with self.assertRaises(DeserializationError):
  89. for obj in serializers.deserialize("json", """[{"pk":1}"""):
  90. pass
  91. def test_helpful_error_message_invalid_pk(self):
  92. """
  93. If there is an invalid primary key, the error message should contain
  94. the model associated with it.
  95. """
  96. test_string = """[{
  97. "pk": "badpk",
  98. "model": "serializers.player",
  99. "fields": {
  100. "name": "Bob",
  101. "rank": 1,
  102. "team": "Team"
  103. }
  104. }]"""
  105. with self.assertRaisesMessage(DeserializationError, "(serializers.player:pk=badpk)"):
  106. list(serializers.deserialize('json', test_string))
  107. def test_helpful_error_message_invalid_field(self):
  108. """
  109. If there is an invalid field value, the error message should contain
  110. the model associated with it.
  111. """
  112. test_string = """[{
  113. "pk": "1",
  114. "model": "serializers.player",
  115. "fields": {
  116. "name": "Bob",
  117. "rank": "invalidint",
  118. "team": "Team"
  119. }
  120. }]"""
  121. expected = "(serializers.player:pk=1) field_value was 'invalidint'"
  122. with self.assertRaisesMessage(DeserializationError, expected):
  123. list(serializers.deserialize('json', test_string))
  124. def test_helpful_error_message_for_foreign_keys(self):
  125. """
  126. Invalid foreign keys with a natural key should throw a helpful error
  127. message, such as what the failing key is.
  128. """
  129. test_string = """[{
  130. "pk": 1,
  131. "model": "serializers.category",
  132. "fields": {
  133. "name": "Unknown foreign key",
  134. "meta_data": [
  135. "doesnotexist",
  136. "metadata"
  137. ]
  138. }
  139. }]"""
  140. key = ["doesnotexist", "metadata"]
  141. expected = "(serializers.category:pk=1) field_value was '%r'" % key
  142. with self.assertRaisesMessage(DeserializationError, expected):
  143. list(serializers.deserialize('json', test_string))
  144. def test_helpful_error_message_for_many2many_non_natural(self):
  145. """
  146. Invalid many-to-many keys should throw a helpful error message.
  147. """
  148. test_string = """[{
  149. "pk": 1,
  150. "model": "serializers.article",
  151. "fields": {
  152. "author": 1,
  153. "headline": "Unknown many to many",
  154. "pub_date": "2014-09-15T10:35:00",
  155. "categories": [1, "doesnotexist"]
  156. }
  157. }, {
  158. "pk": 1,
  159. "model": "serializers.author",
  160. "fields": {
  161. "name": "Agnes"
  162. }
  163. }, {
  164. "pk": 1,
  165. "model": "serializers.category",
  166. "fields": {
  167. "name": "Reference"
  168. }
  169. }]"""
  170. expected = "(serializers.article:pk=1) field_value was 'doesnotexist'"
  171. with self.assertRaisesMessage(DeserializationError, expected):
  172. list(serializers.deserialize('json', test_string))
  173. def test_helpful_error_message_for_many2many_natural1(self):
  174. """
  175. Invalid many-to-many keys should throw a helpful error message.
  176. This tests the code path where one of a list of natural keys is invalid.
  177. """
  178. test_string = """[{
  179. "pk": 1,
  180. "model": "serializers.categorymetadata",
  181. "fields": {
  182. "kind": "author",
  183. "name": "meta1",
  184. "value": "Agnes"
  185. }
  186. }, {
  187. "pk": 1,
  188. "model": "serializers.article",
  189. "fields": {
  190. "author": 1,
  191. "headline": "Unknown many to many",
  192. "pub_date": "2014-09-15T10:35:00",
  193. "meta_data": [
  194. ["author", "meta1"],
  195. ["doesnotexist", "meta1"],
  196. ["author", "meta1"]
  197. ]
  198. }
  199. }, {
  200. "pk": 1,
  201. "model": "serializers.author",
  202. "fields": {
  203. "name": "Agnes"
  204. }
  205. }]"""
  206. key = ["doesnotexist", "meta1"]
  207. expected = "(serializers.article:pk=1) field_value was '%r'" % key
  208. with self.assertRaisesMessage(DeserializationError, expected):
  209. for obj in serializers.deserialize('json', test_string):
  210. obj.save()
  211. def test_helpful_error_message_for_many2many_natural2(self):
  212. """
  213. Invalid many-to-many keys should throw a helpful error message. This
  214. tests the code path where a natural many-to-many key has only a single
  215. value.
  216. """
  217. test_string = """[{
  218. "pk": 1,
  219. "model": "serializers.article",
  220. "fields": {
  221. "author": 1,
  222. "headline": "Unknown many to many",
  223. "pub_date": "2014-09-15T10:35:00",
  224. "meta_data": [1, "doesnotexist"]
  225. }
  226. }, {
  227. "pk": 1,
  228. "model": "serializers.categorymetadata",
  229. "fields": {
  230. "kind": "author",
  231. "name": "meta1",
  232. "value": "Agnes"
  233. }
  234. }, {
  235. "pk": 1,
  236. "model": "serializers.author",
  237. "fields": {
  238. "name": "Agnes"
  239. }
  240. }]"""
  241. expected = "(serializers.article:pk=1) field_value was 'doesnotexist'"
  242. with self.assertRaisesMessage(DeserializationError, expected):
  243. for obj in serializers.deserialize('json', test_string, ignore=False):
  244. obj.save()
  245. class JsonSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase):
  246. serializer_name = "json"
  247. fwd_ref_str = """[
  248. {
  249. "pk": 1,
  250. "model": "serializers.article",
  251. "fields": {
  252. "headline": "Forward references pose no problem",
  253. "pub_date": "2006-06-16T15:00:00",
  254. "categories": [1],
  255. "author": 1
  256. }
  257. },
  258. {
  259. "pk": 1,
  260. "model": "serializers.category",
  261. "fields": {
  262. "name": "Reference"
  263. }
  264. },
  265. {
  266. "pk": 1,
  267. "model": "serializers.author",
  268. "fields": {
  269. "name": "Agnes"
  270. }
  271. }]"""
  272. class DjangoJSONEncoderTests(SimpleTestCase):
  273. def test_lazy_string_encoding(self):
  274. self.assertEqual(
  275. json.dumps({'lang': ugettext_lazy("French")}, cls=DjangoJSONEncoder),
  276. '{"lang": "French"}'
  277. )
  278. with override('fr'):
  279. self.assertEqual(
  280. json.dumps({'lang': ugettext_lazy("French")}, cls=DjangoJSONEncoder),
  281. '{"lang": "Fran\\u00e7ais"}'
  282. )
  283. def test_timedelta(self):
  284. duration = datetime.timedelta(days=1, hours=2, seconds=3)
  285. self.assertEqual(
  286. json.dumps({'duration': duration}, cls=DjangoJSONEncoder),
  287. '{"duration": "P1DT02H00M03S"}'
  288. )
  289. duration = datetime.timedelta(0)
  290. self.assertEqual(
  291. json.dumps({'duration': duration}, cls=DjangoJSONEncoder),
  292. '{"duration": "P0DT00H00M00S"}'
  293. )