Coverage for tests/test_streams.py: 100%

60 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-05-26 23:07 +0100

1import httpx 

2import pytest 

3 

4 

5def byteiterator(buffer=b""): 

6 for num in buffer: 

7 yield chr(num) 

8 

9 

10def test_bytestream(): 

11 s = httpx.ByteStream(b"1234567890") 

12 assert repr(s) == "<ByteStream [10B]>" 

13 assert s.size == 10 

14 

15 s = httpx.ByteStream(b"1234567890" * 1024) 

16 assert repr(s) == "<ByteStream [10KB]>" 

17 assert s.size == 10 * 1024 

18 

19 s = httpx.ByteStream(b"1234567890" * 1024 * 1024) 

20 assert repr(s) == "<ByteStream [10MB]>" 

21 assert s.size == 10 * 1024 * 1024 

22 

23 

24def test_bytestream_iter(): 

25 s = httpx.ByteStream(b"1234567890") 

26 for _ in s: 

27 assert _ == b"1234567890" 

28 

29 

30def test_iterbytestream_unknown_size(): 

31 s = httpx.IterByteStream(byteiterator(b"1234567890")) 

32 assert s.size == None 

33 assert repr(s) == "<IterByteStream [0% of ???]>" 

34 

35 for _ in s: 

36 assert repr(s) == "<IterByteStream [???% of ???]>" 

37 assert repr(s) == "<IterByteStream [100% of 10B]>" 

38 

39 

40def test_iterbytestream_fixed_size(): 

41 s = httpx.IterByteStream(byteiterator(b"1234567890"), size=10) 

42 assert s.size == 10 

43 assert repr(s) == "<IterByteStream [0% of 10B]>" 

44 

45 for idx, _ in enumerate(s, start=1): 

46 percent = idx * 10 

47 assert repr(s) == f"<IterByteStream [{percent}% of 10B]>" 

48 assert repr(s) == "<IterByteStream [100% of 10B]>" 

49 

50 

51def test_iterbytestream_validates_size(): 

52 s = httpx.IterByteStream(byteiterator(b"1234567890"), size=5) 

53 with pytest.raises(ValueError): 

54 for _ in s: 

55 pass 

56 

57 s = httpx.IterByteStream(byteiterator(b"1234567890"), size=15) 

58 with pytest.raises(ValueError): 

59 for _ in s: 

60 pass 

61 

62 

63def test_humanized_size_repr(): 

64 s = httpx.IterByteStream(byteiterator(), size=1) 

65 assert repr(s) == "<IterByteStream [0% of 1B]>" 

66 

67 s = httpx.IterByteStream(byteiterator(), size=1024) 

68 assert repr(s) == "<IterByteStream [0% of 1KB]>" 

69 

70 s = httpx.IterByteStream(byteiterator(), size=1024 ** 2) 

71 assert repr(s) == "<IterByteStream [0% of 1MB]>" 

72 

73 s = httpx.IterByteStream(byteiterator(), size=1024 ** 3) 

74 assert repr(s) == "<IterByteStream [0% of 1GB]>" 

75 

76 s = httpx.IterByteStream(byteiterator(), size=1024 ** 4) 

77 assert repr(s) == "<IterByteStream [0% of 1TB]>" 

78 

79 

80def test_stream_interface(): 

81 stream = httpx.Stream() 

82 

83 with pytest.raises(NotImplementedError): 

84 stream.size 

85 

86 with pytest.raises(NotImplementedError): 

87 [_ for _ in stream]