test_utils.py 3.0 KB

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