test_tool.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. from __future__ import with_statement
  2. import os
  3. import sys
  4. import textwrap
  5. import unittest
  6. import subprocess
  7. import tempfile
  8. try:
  9. # Python 3.x
  10. from test.support import strip_python_stderr
  11. except ImportError:
  12. # Python 2.6+
  13. try:
  14. from test.test_support import strip_python_stderr
  15. except ImportError:
  16. # Python 2.5
  17. import re
  18. def strip_python_stderr(stderr):
  19. return re.sub(
  20. r"\[\d+ refs\]\r?\n?$".encode(),
  21. "".encode(),
  22. stderr).strip()
  23. class TestTool(unittest.TestCase):
  24. data = """
  25. [["blorpie"],[ "whoops" ] , [
  26. ],\t"d-shtaeou",\r"d-nthiouh",
  27. "i-vhbjkhnth", {"nifty":87}, {"morefield" :\tfalse,"field"
  28. :"yes"} ]
  29. """
  30. expect = textwrap.dedent("""\
  31. [
  32. [
  33. "blorpie"
  34. ],
  35. [
  36. "whoops"
  37. ],
  38. [],
  39. "d-shtaeou",
  40. "d-nthiouh",
  41. "i-vhbjkhnth",
  42. {
  43. "nifty": 87
  44. },
  45. {
  46. "field": "yes",
  47. "morefield": false
  48. }
  49. ]
  50. """)
  51. def runTool(self, args=None, data=None):
  52. argv = [sys.executable, '-m', 'simplejson.tool']
  53. if args:
  54. argv.extend(args)
  55. proc = subprocess.Popen(argv,
  56. stdin=subprocess.PIPE,
  57. stderr=subprocess.PIPE,
  58. stdout=subprocess.PIPE)
  59. out, err = proc.communicate(data)
  60. self.assertEqual(strip_python_stderr(err), ''.encode())
  61. self.assertEqual(proc.returncode, 0)
  62. return out
  63. def test_stdin_stdout(self):
  64. self.assertEqual(
  65. self.runTool(data=self.data.encode()),
  66. self.expect.encode())
  67. def test_infile_stdout(self):
  68. with tempfile.NamedTemporaryFile() as infile:
  69. infile.write(self.data.encode())
  70. infile.flush()
  71. self.assertEqual(
  72. self.runTool(args=[infile.name]),
  73. self.expect.encode())
  74. def test_infile_outfile(self):
  75. with tempfile.NamedTemporaryFile() as infile:
  76. infile.write(self.data.encode())
  77. infile.flush()
  78. # outfile will get overwritten by tool, so the delete
  79. # may not work on some platforms. Do it manually.
  80. outfile = tempfile.NamedTemporaryFile()
  81. try:
  82. self.assertEqual(
  83. self.runTool(args=[infile.name, outfile.name]),
  84. ''.encode())
  85. with open(outfile.name, 'rb') as f:
  86. self.assertEqual(f.read(), self.expect.encode())
  87. finally:
  88. outfile.close()
  89. if os.path.exists(outfile.name):
  90. os.unlink(outfile.name)