Coverage for tests/test_network.py: 100%

27 statements  

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

1import httpx 

2 

3 

4def echo(stream): 

5 while buffer := stream.read(): 

6 stream.write(buffer) 

7 

8 

9def test_network_backend(): 

10 net = httpx.NetworkBackend() 

11 assert repr(net) == "<NetworkBackend [threaded]>" 

12 

13 

14def test_network_backend_connect(): 

15 with httpx.serve_tcp(echo) as server: 

16 host, port = (server.host, server.port) 

17 net = httpx.NetworkBackend() 

18 stream = net.connect(host, port) 

19 try: 

20 assert repr(stream) == f"<NetworkStream ['{host}:{port}']>" 

21 stream.write(b"Hello, world.") 

22 content = stream.read() 

23 assert content == b"Hello, world." 

24 finally: 

25 stream.close() 

26 

27 

28def test_network_backend_context_managed(): 

29 with httpx.serve_tcp(echo) as server: 

30 host, port = (server.host, server.port) 

31 net = httpx.NetworkBackend() 

32 with net.connect(server.host, server.port) as stream: 

33 stream.write(b"Hello, world.") 

34 content = stream.read() 

35 assert content == b"Hello, world." 

36 assert repr(stream) == f"<NetworkStream ['{host}:{port}' CLOSED]>" 

37 

38 

39# >>> net = httpx.NetworkBackend() 

40# >>> stream = net.connect("dev.encode.io", 80) 

41# >>> try: 

42# >>> ... 

43# >>> finally: 

44# >>> stream.close() 

45# >>> stream 

46# <NetworkStream ["168.0.0.1:80" CLOSED]> 

47 

48# import httpx 

49# import ssl 

50# import truststore 

51 

52# net = httpx.NetworkBackend() 

53# ctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) 

54# req = b'\r\n'.join([ 

55# b'GET / HTTP/1.1', 

56# b'Host: www.example.com', 

57# b'User-Agent: python/dev', 

58# b'Connection: close', 

59# b'', 

60# ]) 

61 

62# # Use a 10 second overall timeout for the entire request/response. 

63# with timeout(10.0): 

64# # Use a 3 second timeout for the initial connection. 

65# with timeout(3.0) as t: 

66# # Open the connection & establish SSL. 

67# with net.open_stream("www.example.com", 443) as stream: 

68# stream.start_tls(ctx, hostname="www.example.com") 

69# t.cancel() 

70# # Send the request & read the response. 

71# stream.write(req) 

72# buffer = [] 

73# while part := stream.read(): 

74# buffer.append(part) 

75# resp = b''.join(buffer) 

76 

77 

78# def test_fixture(tcp_echo_server): 

79# host, port = (tcp_echo_server.host, tcp_echo_server.port) 

80 

81# net = httpx.NetworkBackend() 

82# with net.connect(host, port) as stream: 

83# stream.write(b"123") 

84# buffer = stream.read() 

85# assert buffer == b"123"