Skip to content

Commit

Permalink
show pytest fixture as tag (#148)
Browse files Browse the repository at this point in the history
  • Loading branch information
cle-b authored Oct 11, 2024
1 parent a8797ae commit 87afec0
Show file tree
Hide file tree
Showing 15 changed files with 135 additions and 17 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ Clic on the **⚙** button on the top right of the page.
Some options are available:
* Hide the netloc in the url
* Hide the initiator rows
* Hide the tags

To keep your configuration, bookmark the page with the full search query.

Expand Down
2 changes: 1 addition & 1 deletion httpdbg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
from httpdbg.records import HTTPRecords


__version__ = "0.23.0"
__version__ = "0.24.0"

__all__ = ["httprecord", "HTTPRecords"]
4 changes: 4 additions & 0 deletions httpdbg/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
HTTPDBG_CURRENT_INITIATOR = "HTTPDBG_CURRENT_INITIATOR"
HTTPDBG_CURRENT_TAG = "HTTPDBG_CURRENT_TAG"
HTTPDBG_LOG = "HTTPDBG_LOG"
HTTPDBG_SUBPROCESS_DIR = "HTTPDBG_SUBPROCESS_DIR"
8 changes: 5 additions & 3 deletions httpdbg/hooks/all.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
from typing import Union

from httpdbg.hooks.aiohttp import hook_aiohttp
from httpdbg.hooks.external import watcher_external
from httpdbg.hooks.generic import hook_generic
from httpdbg.hooks.httpx import hook_httpx
from httpdbg.hooks.pytest import hook_pytest
from httpdbg.hooks.requests import hook_requests
from httpdbg.hooks.socket import hook_socket
from httpdbg.hooks.external import watcher_external
from httpdbg.hooks.urllib3 import hook_urllib3
from httpdbg.records import HTTPRecords

Expand All @@ -27,5 +28,6 @@ def httprecord(
with hook_requests(records):
with hook_urllib3(records):
with hook_aiohttp(records):
with hook_generic(records, initiators):
yield records
with hook_pytest(records):
with hook_generic(records, initiators):
yield records
9 changes: 4 additions & 5 deletions httpdbg/hooks/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,18 @@
import time
import threading

from httpdbg.env import HTTPDBG_SUBPROCESS_DIR
from httpdbg.records import HTTPRecords


@contextmanager
def watcher_external(records: HTTPRecords) -> Generator[HTTPRecords, None, None]:
try:
if "HTTPDBG_SUBPROCESS_DIR" not in os.environ:
if HTTPDBG_SUBPROCESS_DIR not in os.environ:
with tempfile.TemporaryDirectory(
prefix="httpdbg"
) as httpdbg_subprocess_dir:
os.environ["HTTPDBG_SUBPROCESS_DIR"] = httpdbg_subprocess_dir
os.environ[HTTPDBG_SUBPROCESS_DIR] = httpdbg_subprocess_dir

watcher = WatcherSubprocessDirThread(records)
watcher.start()
Expand All @@ -43,9 +44,7 @@ def __init__(self, records: HTTPRecords, delay: int = 2) -> None:
threading.Thread.__init__(self)

def load_dump(self):
for dump in glob.glob(
f"{os.environ['HTTPDBG_SUBPROCESS_DIR']}/*.httpdbgrecords"
):
for dump in glob.glob(f"{os.environ[HTTPDBG_SUBPROCESS_DIR]}/*.httpdbgrecords"):
with open(dump, "rb") as dumpfile:
newrecords = pickle.load(dumpfile)
self.records.requests.update(newrecords.requests)
Expand Down
51 changes: 51 additions & 0 deletions httpdbg/hooks/pytest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from typing import Generator

from httpdbg.hooks.utils import decorate
from httpdbg.hooks.utils import getcallargs
from httpdbg.hooks.utils import undecorate
from httpdbg.initiator import httpdbg_tag
from httpdbg.records import HTTPRecords


def set_hook_for_pytest_fixture(_, method):
def hook(*args, **kwargs):
callargs = getcallargs(method, *args, **kwargs)

if "fixturefunc" in callargs:
with httpdbg_tag(getattr(callargs["fixturefunc"], "__name__", "fixture")):
return method(*args, **kwargs)
else:
return method(*args, **kwargs)

return hook


@contextmanager
def hook_pytest(records: HTTPRecords) -> Generator[None, None, None]:
hooks = False
try:
import _pytest.fixtures

_pytest.fixtures.call_fixture_func = decorate(
records, _pytest.fixtures.call_fixture_func, set_hook_for_pytest_fixture
)
_pytest.fixtures._teardown_yield_fixture = decorate(
records,
_pytest.fixtures._teardown_yield_fixture,
set_hook_for_pytest_fixture,
)
hooks = True
except ImportError:
pass

yield

if hooks:
_pytest.fixtures.call_fixture_func = undecorate(
_pytest.fixtures.call_fixture_func
)
_pytest.fixtures._teardown_yield_fixture = undecorate(
_pytest.fixtures._teardown_yield_fixture
)
18 changes: 17 additions & 1 deletion httpdbg/initiator.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from typing import Tuple
from typing import Union

from httpdbg.env import HTTPDBG_CURRENT_INITIATOR
from httpdbg.env import HTTPDBG_CURRENT_TAG
from httpdbg.hooks.utils import getcallargs
from httpdbg.utils import get_new_uuid
from httpdbg.utils import logger
Expand Down Expand Up @@ -181,7 +183,7 @@ def extract_short_stack_from_file(
def httpdbg_initiator(
records, extracted_stack: traceback.StackSummary, original_method, *args, **kwargs
) -> Generator[Union[Initiator, None], None, None]:
envname = f"HTTPDBG_CURRENT_INITIATOR_{records.id}"
envname = f"{HTTPDBG_CURRENT_INITIATOR}_{records.id}"

if not os.environ.get(envname):
# temporary set a fake initiator env variable to avoid a recursion error
Expand Down Expand Up @@ -217,3 +219,17 @@ def httpdbg_initiator(

else:
yield None


@contextmanager
def httpdbg_tag(tag: str) -> Generator[None, None, None]:

os.environ[HTTPDBG_CURRENT_TAG] = tag

try:
yield
except Exception:
del os.environ[HTTPDBG_CURRENT_TAG]
raise

del os.environ[HTTPDBG_CURRENT_TAG]
5 changes: 4 additions & 1 deletion httpdbg/records.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
from urllib.parse import urlparse
from typing import Dict, List, Tuple, Union

from httpdbg.env import HTTPDBG_CURRENT_INITIATOR
from httpdbg.env import HTTPDBG_CURRENT_TAG
from httpdbg.utils import HTTPDBGCookie
from httpdbg.utils import HTTPDBGHeader
from httpdbg.initiator import in_lib
Expand Down Expand Up @@ -211,6 +213,7 @@ def __init__(self, tbegin: datetime.datetime = None) -> None:
self.response: HTTPRecordResponse = HTTPRecordResponse()
self.ssl: Union[bool, None] = None
self.tbegin: datetime.datetime = datetime.datetime.now(datetime.timezone.utc)
self.tag = os.environ.get(HTTPDBG_CURRENT_TAG)
if tbegin:
self.tbegin = tbegin

Expand Down Expand Up @@ -302,7 +305,7 @@ def __len__(self) -> int:
return len(self.requests)

def get_initiator(self) -> Initiator:
envname = f"HTTPDBG_CURRENT_INITIATOR_{self.id}"
envname = f"{HTTPDBG_CURRENT_INITIATOR}_{self.id}"

if envname in os.environ:
initiator = self._initiators[os.environ[envname]]
Expand Down
4 changes: 3 additions & 1 deletion httpdbg/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
import string
from typing import List

from httpdbg.env import HTTPDBG_LOG

logger = logging.getLogger("httpdbg")
logger.setLevel(100)
log_level = os.environ.get("HTTPDBG_LOG")
log_level = os.environ.get(HTTPDBG_LOG)
if log_level is not None:
logging.basicConfig(level=int(log_level), format="%(message)s")
logger.setLevel(int(log_level))
Expand Down
2 changes: 2 additions & 0 deletions httpdbg/webapp/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def default(self, req: HTTPRecord) -> Dict[str, Any]:
"request": None,
"response": None,
"exception": None,
"tag": req.tag,
"initiator": req.initiator.to_json(),
"in_progress": req.in_progress,
}
Expand Down Expand Up @@ -74,6 +75,7 @@ def default(self, records):
"status_code": req.status_code,
"reason": req.reason,
"verb": req.method,
"tag": req.tag,
"initiator": req.initiator.to_json(full=False),
"in_progress": req.in_progress,
"tbegin": req.tbegin.isoformat(),
Expand Down
3 changes: 3 additions & 0 deletions httpdbg/webapp/static/configuration.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ function apply_config() {

apply_config_rule_css(httpdbgApp.config.hide_netloc, sheet);
apply_config_rule_css(httpdbgApp.config.hide_initiator, sheet);
apply_config_rule_css(httpdbgApp.config.hide_tag, sheet);

apply_config_rule_click(httpdbgApp.config.details_wrap_default);
apply_config_rule_click(httpdbgApp.config.details_raw_default);
Expand All @@ -48,6 +49,7 @@ function load_config_from_url(apply) {

load_config_rule_from_url(httpdbgApp.config.hide_netloc, params);
load_config_rule_from_url(httpdbgApp.config.hide_initiator, params);
load_config_rule_from_url(httpdbgApp.config.hide_tag, params);
load_config_rule_from_url(httpdbgApp.config.details_wrap_default, params);
load_config_rule_from_url(httpdbgApp.config.details_raw_default, params);

Expand All @@ -65,6 +67,7 @@ function load_config_from_form(apply) {

load_config_rule_from_form(httpdbgApp.config.hide_netloc);
load_config_rule_from_form(httpdbgApp.config.hide_initiator);
load_config_rule_from_form(httpdbgApp.config.hide_tag);
load_config_rule_from_form(httpdbgApp.config.details_wrap_default);
load_config_rule_from_form(httpdbgApp.config.details_raw_default);

Expand Down
12 changes: 11 additions & 1 deletion httpdbg/webapp/static/index.htm
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ <h4>configuration</h4>

<input type="checkbox" id="cinitiator" name="hi" onchange="load_config_from_form(true)">
<label for="cinitiator">Hide the initiator rows</label>

<br>

<input type="checkbox" id="ctag" name="ht" onchange="load_config_from_form(true)">
<label for="ctag">Hide the tags</label>
</fieldset>
</div>
<div>
Expand Down Expand Up @@ -179,7 +184,12 @@ <h4>About</h4>
</td>
<td class="status"><span title="{{reason}}" data-qa-request-status>{{{status_code_view}}}</span></td>
<td class="method"><span title="{{verb}}" data-qa-request-method>{{verb}}</span></td>
<td class="url" title="{{title}}"><span data-qa-request-url><span class="netloc">{{netloc}}</span><span>{{urlext}}</span></span></td>
<td class="url" title="{{title}}">
<span class="url-content" data-qa-request-url>
<span class="netloc">{{netloc}}</span><span>{{urlext}}</span>
</span>
{{#tag}}<span class="tag">{{tag}}</span>{{/tag}}
</td>
</tr>
</script>

Expand Down
6 changes: 6 additions & 0 deletions httpdbg/webapp/static/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ let httpdbgApp = {
"css": ".netloc {display: none;}",
"value": false
},
"hide_tag": {
"checkbox": "ctag",
"param": "ht",
"css": ".tag {display: none;}",
"value": false
},
"details_wrap_default": {
"checkbox": "cwrap",
"param": "wl",
Expand Down
2 changes: 2 additions & 0 deletions httpdbg/webapp/static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
--preview-code-border: #777777;
--column-border: #dadada;
--kdb-border: #000000;
--tag-bg-color: #cf4b8f;
--tag-text: #ffffff;
}

body {
Expand Down
25 changes: 21 additions & 4 deletions httpdbg/webapp/static/table.css
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,30 @@
}

.url {
display: flex;
flex-wrap: wrap;
align-items: center;
text-align: left;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
width: auto;
}

.url-content {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

.tag {
margin-left: 6px;
color: var(--tag-text);
background-color: var(--tag-bg-color);
border-radius: 20%;
padding: 1px 2px;
font-size: 0.8em;
}

.initiator-label {
white-space: nowrap;
overflow: hidden;
Expand Down Expand Up @@ -75,7 +92,7 @@
}

.initiator {
background-color: var(--table-initiator);
background-color: var(--table-initiator);
}

.request {
Expand Down Expand Up @@ -119,7 +136,7 @@
width: 16px;
padding: 2px !important;
transform: rotate(180deg);
background-color: var(--table-initiator);
background-color: var(--table-initiator);
opacity: 0.4;
}

Expand Down

0 comments on commit 87afec0

Please sign in to comment.