test_utils.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. from django.http import QueryDict
  2. from django.test import TestCase
  3. from utilities.data import deepmerge
  4. from utilities.querydict import normalize_querydict
  5. from utilities.utils import dict_to_filter_params
  6. class DictToFilterParamsTest(TestCase):
  7. """
  8. Validate the operation of dict_to_filter_params().
  9. """
  10. def test_dict_to_filter_params(self):
  11. input = {
  12. 'a': True,
  13. 'foo': {
  14. 'bar': 123,
  15. 'baz': 456,
  16. },
  17. 'x': {
  18. 'y': {
  19. 'z': False
  20. }
  21. }
  22. }
  23. output = {
  24. 'a': True,
  25. 'foo__bar': 123,
  26. 'foo__baz': 456,
  27. 'x__y__z': False,
  28. }
  29. self.assertEqual(dict_to_filter_params(input), output)
  30. input['x']['y']['z'] = True
  31. self.assertNotEqual(dict_to_filter_params(input), output)
  32. class NormalizeQueryDictTest(TestCase):
  33. """
  34. Validate normalize_querydict() utility function.
  35. """
  36. def test_normalize_querydict(self):
  37. self.assertDictEqual(
  38. normalize_querydict(QueryDict('foo=1&bar=2&bar=3&baz=')),
  39. {'foo': '1', 'bar': ['2', '3'], 'baz': ''}
  40. )
  41. class DeepMergeTest(TestCase):
  42. """
  43. Validate the behavior of the deepmerge() utility.
  44. """
  45. def test_deepmerge(self):
  46. dict1 = {
  47. 'active': True,
  48. 'foo': 123,
  49. 'fruits': {
  50. 'orange': 1,
  51. 'apple': 2,
  52. 'pear': 3,
  53. },
  54. 'vegetables': None,
  55. 'dairy': {
  56. 'milk': 1,
  57. 'cheese': 2,
  58. },
  59. 'deepnesting': {
  60. 'foo': {
  61. 'a': 10,
  62. 'b': 20,
  63. 'c': 30,
  64. },
  65. },
  66. }
  67. dict2 = {
  68. 'active': False,
  69. 'bar': 456,
  70. 'fruits': {
  71. 'banana': 4,
  72. 'grape': 5,
  73. },
  74. 'vegetables': {
  75. 'celery': 1,
  76. 'carrots': 2,
  77. 'corn': 3,
  78. },
  79. 'dairy': None,
  80. 'deepnesting': {
  81. 'foo': {
  82. 'a': 100,
  83. 'd': 40,
  84. },
  85. },
  86. }
  87. merged = {
  88. 'active': False,
  89. 'foo': 123,
  90. 'bar': 456,
  91. 'fruits': {
  92. 'orange': 1,
  93. 'apple': 2,
  94. 'pear': 3,
  95. 'banana': 4,
  96. 'grape': 5,
  97. },
  98. 'vegetables': {
  99. 'celery': 1,
  100. 'carrots': 2,
  101. 'corn': 3,
  102. },
  103. 'dairy': None,
  104. 'deepnesting': {
  105. 'foo': {
  106. 'a': 100,
  107. 'b': 20,
  108. 'c': 30,
  109. 'd': 40,
  110. },
  111. },
  112. }
  113. self.assertEqual(
  114. deepmerge(dict1, dict2),
  115. merged
  116. )