test_jsonutils.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # -*- coding: utf-8 -*-
  2. import os
  3. from boltons.jsonutils import (JSONLIterator,
  4. DEFAULT_BLOCKSIZE,
  5. reverse_iter_lines)
  6. CUR_PATH = os.path.dirname(os.path.abspath(__file__))
  7. NEWLINES_DATA_PATH = CUR_PATH + '/newlines_test_data.txt'
  8. JSONL_DATA_PATH = CUR_PATH + '/jsonl_test_data.txt'
  9. def _test_reverse_iter_lines(filename, blocksize=DEFAULT_BLOCKSIZE):
  10. fo = open(filename)
  11. reference = fo.read()
  12. fo.seek(0, os.SEEK_SET)
  13. rev_lines = list(reverse_iter_lines(fo, blocksize))
  14. assert '\n'.join(rev_lines[::-1]) == reference
  15. def _test_reverse_iter_lines_bytes(filename, blocksize=DEFAULT_BLOCKSIZE):
  16. fo = open(filename, 'rb')
  17. reference = fo.read()
  18. fo.seek(0, os.SEEK_SET)
  19. rev_lines = list(reverse_iter_lines(fo, blocksize))
  20. assert os.linesep.encode('ascii').join(rev_lines[::-1]) == reference
  21. def test_reverse_iter_lines():
  22. for blocksize in (2, 4, 16, 4096):
  23. _test_reverse_iter_lines(NEWLINES_DATA_PATH, blocksize)
  24. _test_reverse_iter_lines_bytes(NEWLINES_DATA_PATH, blocksize)
  25. def test_jsonl_iterator():
  26. ref = [{u'4': 4}, {u'3': 3}, {u'2': 2}, {u'1': 1}, {}]
  27. jsonl_iter = JSONLIterator(open(JSONL_DATA_PATH), reverse=True)
  28. jsonl_list = list(jsonl_iter)
  29. assert jsonl_list == ref