test_jsonl.py 9.6 KB

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