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