test_utils.py 2.7 KB

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