Skip to content

Commit

Permalink
add ut in django (#554)
Browse files Browse the repository at this point in the history
  • Loading branch information
eeliu committed Mar 28, 2024
1 parent 0627af7 commit 3d1869c
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 12 deletions.
17 changes: 17 additions & 0 deletions plugins/PY/pinpointPy/Common.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,23 @@ def getUniqueName(self):
return self.name


class TraceIdObject:
def __init__(self, id: int) -> None:
self.traceId = id


class PinTraceV1(PinTrace):
def onBefore(self, parentId: int, *args, **kwargs):
trace_id, args, kwargs = super().onBefore(parentId, *args, **kwargs)
return TraceIdObject(trace_id), args, kwargs

def onEnd(self, traceIdObj: TraceIdObject, ret):
return super().onEnd(traceIdObj.traceId, ret)

def onException(self, traceId: TraceIdObject, e):
raise NotImplementedError()


class PinHeader:
def __init__(self) -> None:
# Path field in pinpoint-web
Expand Down
24 changes: 17 additions & 7 deletions plugins/PY/pinpointPy/Django/BaseDjangoRequestPlugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,18 @@
from pinpointPy import Common, Defines, pinpoint


class BaseDjangoRequestPlugins(Common.PinTrace):
class BaseDjangoRequestPlugins(Common.PinTraceV1):
def __init__(self, name):
super().__init__(name)

@staticmethod
def isSample(*args, **kwargs):
return True, 0, args, kwargs

# -> tuple[TraceIdObject, tuple[Any, ...], dict[str, Any]]:
def onBefore(self, parentId, *args, **kwargs):
trace_id, args, kwargs = super().onBefore(parentId, *args, **kwargs)
trace_id_object, args, kwargs = super().onBefore(parentId, *args, **kwargs)
trace_id = trace_id_object.traceId
pinpoint.add_trace_header(
Defines.PP_APP_NAME, pinpoint.app_name(), trace_id)
pinpoint.add_trace_header(
Expand All @@ -40,6 +42,7 @@ def onBefore(self, parentId, *args, **kwargs):
pinpoint.app_name(), trace_id)
###############################################################
request = args[0]
trace_id_object._request_ = request
headers = request.META

# assert isinstance(request,BaseHTTPRequestHandler)
Expand Down Expand Up @@ -138,17 +141,24 @@ def onBefore(self, parentId, *args, **kwargs):
Defines.PP_HTTP_METHOD, headers["REQUEST_METHOD"], trace_id)

###############################################################
return trace_id, args, kwargs
return trace_id_object, args, kwargs

def onEnd(self, trace_id, ret):
def onEnd(self, traceIdOjb: Common.TraceIdObject, ret):
trace_id = traceIdOjb.traceId
###############################################################
if ret:
pinpoint.add_trace_header_v2(
Defines.PP_HTTP_STATUS_CODE, str(ret.status_code), trace_id)
self._add_ut(trace_id, traceIdOjb._request_, ret)
###############################################################
super().onEnd(trace_id, ret)
super().onEnd(traceIdOjb, ret)
return ret

def onException(self, trace_id, e):
pinpoint.mark_as_error(str(e), "", trace_id)
def onException(self, traceIdOjb: Common.TraceIdObject, e):
pinpoint.mark_as_error(str(e), "", traceIdOjb.trace_id)
raise e

def _add_ut(self, traceId, request, response):
if request.resolver_match:
pinpoint.add_trace_header(Defines.PP_URL_TEMPLATED, str(
request.resolver_match.route), trace_id=traceId)
8 changes: 5 additions & 3 deletions plugins/PY/pinpointPy/pinpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
__logger__ = None


def get_logger() -> logging.Logger:
def get_logger(level=logging.INFO) -> logging.Logger:
global __logger__
if __logger__:
return __logger__
Expand All @@ -38,14 +38,13 @@ def get_logger() -> logging.Logger:
'%(asctime)s %(levelname)s %(message)s')
_, filepath = mkstemp(prefix="pinpoint")
import sys
import os
if 'unittest' in sys.modules.keys():
file_handler = logging.FileHandler(filepath)
print(filepath)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
elif 'pinpoint-debug' in os.environ and os.environ['pinpoint-debug']:
elif level == logging.DEBUG:
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
Expand Down Expand Up @@ -128,5 +127,8 @@ def set_agent(app_id_str: str, app_name_str: str, collect_agent_host: str, trac
def debug_func(msg: str):
get_logger().debug(msg=msg)
_pinpointPy.enable_debug(debug_func)
global __logger__
__logger__ = None
get_logger(log_level)
get_logger().debug(
f"appid:{app_id_str} appname:{app_name_str} collector_agent:{collect_agent_host} trace_limit:{trace_limit} log_level:{log_level}")
5 changes: 3 additions & 2 deletions testapps/django/mysite/mysite/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from pinpointPy import set_agent, monkey_patch_for_pinpoint, use_thread_local_context
from pathlib import Path
import logging

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
Expand Down Expand Up @@ -44,8 +45,8 @@

use_thread_local_context()
monkey_patch_for_pinpoint()
set_agent("cd.dev.test.py", "cd.dev.test.py", 'tcp:dev-collector:10000', -1)

set_agent("cd.dev.test.py", "cd.dev.test.py",
'tcp:dev-collector:10000', -1, logging.DEBUG)

MIDDLEWARE = [
'pinpointPy.Django.DjangoMiddleWare',
Expand Down
1 change: 1 addition & 0 deletions testapps/django/mysite/polls/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@

urlpatterns = [
path("", views.index, name="index"),
path('products/<int:pk>/', views.get_products, name="index"),
]
6 changes: 6 additions & 0 deletions testapps/django/mysite/polls/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
from django.http import HttpResponse
from django.http.request import HttpRequest


def index(request):
return HttpResponse("Hello, world. You're at the polls index.")


def get_products(request, pk):
assert isinstance(request, HttpRequest)
return HttpResponse(f"product: {pk}")

0 comments on commit 3d1869c

Please sign in to comment.