test_json.py 9.6 KB

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