jsonmodify_test.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2022 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. """Tests for jsonmodify."""
  18. import json
  19. import jsonmodify
  20. import unittest
  21. class JsonmodifyTest(unittest.TestCase):
  22. def test_set_value(self):
  23. obj = json.loads('{"field1": 111}')
  24. field1 = jsonmodify.SetValue("field1")
  25. field1.apply(obj, 222)
  26. field2 = jsonmodify.SetValue("field2")
  27. field2.apply(obj, 333)
  28. expected = json.loads('{"field1": 222, "field2": 333}')
  29. self.assertEqual(obj, expected)
  30. def test_replace(self):
  31. obj = json.loads('{"field1": 111}')
  32. field1 = jsonmodify.Replace("field1")
  33. field1.apply(obj, 222)
  34. field2 = jsonmodify.Replace("field2")
  35. field2.apply(obj, 333)
  36. expected = json.loads('{"field1": 222}')
  37. self.assertEqual(obj, expected)
  38. def test_replace_if_equal(self):
  39. obj = json.loads('{"field1": 111, "field2": 222}')
  40. field1 = jsonmodify.ReplaceIfEqual("field1")
  41. field1.apply(obj, 111, 333)
  42. field2 = jsonmodify.ReplaceIfEqual("field2")
  43. field2.apply(obj, 444, 555)
  44. field3 = jsonmodify.ReplaceIfEqual("field3")
  45. field3.apply(obj, 666, 777)
  46. expected = json.loads('{"field1": 333, "field2": 222}')
  47. self.assertEqual(obj, expected)
  48. def test_remove(self):
  49. obj = json.loads('{"field1": 111, "field2": 222}')
  50. field2 = jsonmodify.Remove("field2")
  51. field2.apply(obj)
  52. field3 = jsonmodify.Remove("field3")
  53. field3.apply(obj)
  54. expected = json.loads('{"field1": 111}')
  55. self.assertEqual(obj, expected)
  56. def test_append_list(self):
  57. obj = json.loads('{"field1": [111]}')
  58. field1 = jsonmodify.AppendList("field1")
  59. field1.apply(obj, 222, 333)
  60. field2 = jsonmodify.AppendList("field2")
  61. field2.apply(obj, 444, 555, 666)
  62. expected = json.loads('{"field1": [111, 222, 333], "field2": [444, 555, 666]}')
  63. self.assertEqual(obj, expected)
  64. if __name__ == '__main__':
  65. unittest.main(verbosity=2)