test_streaming.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #
  2. # This file is part of pyasn1 software.
  3. #
  4. # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
  5. # License: https://pyasn1.readthedocs.io/en/latest/license.html
  6. #
  7. import io
  8. import sys
  9. try:
  10. import unittest2 as unittest
  11. except ImportError:
  12. import unittest
  13. from __tests__.base import BaseTestCase
  14. from pyasn1.codec import streaming
  15. class CachingStreamWrapperTestCase(BaseTestCase):
  16. def setUp(self):
  17. self.shortText = b"abcdefghij"
  18. self.longText = self.shortText * (io.DEFAULT_BUFFER_SIZE * 5)
  19. self.shortStream = io.BytesIO(self.shortText)
  20. self.longStream = io.BytesIO(self.longText)
  21. def testReadJustFromCache(self):
  22. wrapper = streaming.CachingStreamWrapper(self.shortStream)
  23. wrapper.read(6)
  24. wrapper.seek(3)
  25. assert wrapper.read(1) == b"d"
  26. assert wrapper.read(1) == b"e"
  27. assert wrapper.tell() == 5
  28. def testReadFromCacheAndStream(self):
  29. wrapper = streaming.CachingStreamWrapper(self.shortStream)
  30. wrapper.read(6)
  31. wrapper.seek(3)
  32. assert wrapper.read(4) == b"defg"
  33. assert wrapper.tell() == 7
  34. def testReadJustFromStream(self):
  35. wrapper = streaming.CachingStreamWrapper(self.shortStream)
  36. assert wrapper.read(6) == b"abcdef"
  37. assert wrapper.tell() == 6
  38. def testPeek(self):
  39. wrapper = streaming.CachingStreamWrapper(self.longStream)
  40. read_bytes = wrapper.peek(io.DEFAULT_BUFFER_SIZE + 73)
  41. assert len(read_bytes) == io.DEFAULT_BUFFER_SIZE + 73
  42. assert read_bytes.startswith(b"abcdefg")
  43. assert wrapper.tell() == 0
  44. assert wrapper.read(4) == b"abcd"
  45. def testMarkedPositionResets(self):
  46. wrapper = streaming.CachingStreamWrapper(self.longStream)
  47. wrapper.read(10)
  48. wrapper.markedPosition = wrapper.tell()
  49. assert wrapper.markedPosition == 10
  50. # Reach the maximum capacity of cache
  51. wrapper.read(io.DEFAULT_BUFFER_SIZE)
  52. assert wrapper.tell() == 10 + io.DEFAULT_BUFFER_SIZE
  53. # The following should clear the cache
  54. wrapper.markedPosition = wrapper.tell()
  55. assert wrapper.markedPosition == 0
  56. assert len(wrapper._cache.getvalue()) == 0
  57. suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
  58. if __name__ == '__main__':
  59. unittest.TextTestRunner(verbosity=2).run(suite)