|
| 1 | +import pytest |
| 2 | + |
1 | 3 | try: |
2 | 4 | from urllib.request import urlopen |
3 | 5 | except ImportError: |
4 | 6 | from urllib import urlopen |
5 | 7 |
|
| 8 | +try: |
| 9 | + from httplib import HTTPConnection |
| 10 | +except ImportError: |
| 11 | + from http.client import HTTPConnection |
| 12 | + |
6 | 13 | from sentry_sdk import capture_message |
7 | 14 | from sentry_sdk.integrations.stdlib import StdlibIntegration |
8 | 15 |
|
@@ -55,3 +62,44 @@ def before_breadcrumb(crumb, hint): |
55 | 62 | "reason": "OK", |
56 | 63 | "extra": "foo", |
57 | 64 | } |
| 65 | + |
| 66 | + |
| 67 | +def test_httplib_misuse(sentry_init, capture_events): |
| 68 | + """HTTPConnection.getresponse must be called after every call to |
| 69 | + HTTPConnection.request. However, if somebody does not abide by |
| 70 | + this contract, we still should handle this gracefully and not |
| 71 | + send mixed breadcrumbs. |
| 72 | +
|
| 73 | + Test whether our breadcrumbs are coherent when somebody uses HTTPConnection |
| 74 | + wrongly. |
| 75 | + """ |
| 76 | + |
| 77 | + sentry_init() |
| 78 | + events = capture_events() |
| 79 | + |
| 80 | + conn = HTTPConnection("httpbin.org", 80) |
| 81 | + conn.request("GET", "/anything/foo") |
| 82 | + |
| 83 | + with pytest.raises(Exception): |
| 84 | + # This raises an exception, because we didn't call `getresponse` for |
| 85 | + # the previous request yet. |
| 86 | + # |
| 87 | + # This call should not affect our breadcrumb. |
| 88 | + conn.request("POST", "/anything/bar") |
| 89 | + |
| 90 | + response = conn.getresponse() |
| 91 | + assert response._method == "GET" |
| 92 | + |
| 93 | + capture_message("Testing!") |
| 94 | + |
| 95 | + event, = events |
| 96 | + crumb, = event["breadcrumbs"] |
| 97 | + |
| 98 | + assert crumb["type"] == "http" |
| 99 | + assert crumb["category"] == "httplib" |
| 100 | + assert crumb["data"] == { |
| 101 | + "url": "http://httpbin.org/anything/foo", |
| 102 | + "method": "GET", |
| 103 | + "status_code": 200, |
| 104 | + "reason": "OK", |
| 105 | + } |
0 commit comments