Coverage for tests/test_client.py: 100%

1 import json

2 import httpx

3 import pytest

4

5

6 def echo(request):

7 request.read()

8 body = None if not request.body else json.loads(request.body)

9 response = httpx.Response(200, content=httpx.JSON({

10 'method': request.method,

11 'query-params': dict(request.url.params.items()),

12 'content-type': request.headers.get('Content-Type'),

13 'json': body,

14 }))

15 return response

16

17

18@pytest.fixture

19 def client():

20 with httpx.open_client() as client:

21 yield client

22

23

24@pytest.fixture

25 def server():

26 with httpx.serve_http(echo) as server:

27 yield server

28

29

30 def test_client(client):

31 assert repr(client) == "<Client [0 active]>"

32

33

34 def test_get(client, server):

35 r = client.get(server.url)

36 assert r.code == 200

37 assert json.loads(r.body) == {

38 'method': 'GET',

39 'query-params': {},

40 'content-type': None,

41 'json': None,

42 }

43

44

45 def test_post(client, server):

46 data = httpx.JSON({"data": 123})

47 r = client.post(server.url, content=data)

48 assert r.code == 200

49 assert json.loads(r.body) == {

50 'method': 'POST',

51 'query-params': {},

52 'content-type': 'application/json',

53 'json': {"data": 123},

54 }

55

56

57 def test_put(client, server):

58 data = httpx.JSON({"data": 123})

59 r = client.put(server.url, content=data)

60 assert r.code == 200

61 assert json.loads(r.body) == {

62 'method': 'PUT',

63 'query-params': {},

64 'content-type': 'application/json',

65 'json': {"data": 123},

66 }

67

68

69 def test_patch(client, server):

70 data = httpx.JSON({"data": 123})

71 r = client.patch(server.url, content=data)

72 assert r.code == 200

73 assert json.loads(r.body) == {

74 'method': 'PATCH',

75 'query-params': {},

76 'content-type': 'application/json',

77 'json': {"data": 123},

78 }

79

80

81 def test_delete(client, server):

82 r = client.delete(server.url)

83 assert r.code == 200

84 assert json.loads(r.body) == {

85 'method': 'DELETE',

86 'query-params': {},

87 'content-type': None,

88 'json': None,

89 }

90

91

92 def test_request(client, server):

93 r = client.request("GET", server.url)

94 assert r.code == 200

95 assert json.loads(r.body) == {

96 'method': 'GET',

97 'query-params': {},

98 'content-type': None,

99 'json': None,

100 }

101

102

103 def test_stream(client, server):

104 with client.stream("GET", server.url) as r:

105 assert r.code == 200

106 r.read()

107 assert json.loads(r.body) == {

108 'method': 'GET',

109 'query-params': {},

110 'content-type': None,

111 'json': None,

112 }