8000 Add Application Insights Django-specific tests by daveta · Pull Request #154 · microsoft/botbuilder-python · GitHub
[go: up one dir, main page]

Skip to content

Add Application Insights Django-specific tests #154

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
# license information.
# --------------------------------------------------------------------------

from .application_insights_telemetry_client import ApplicationInsightsTelemetryClient
from .application_insights_telemetry_client import ApplicationInsightsTelemetryClient, bot_telemetry_processor

__all__ = ["ApplicationInsightsTelemetryClient"]
__all__ = ["ApplicationInsightsTelemetryClient",
"bot_telemetry_processor"
]
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,35 @@
from typing import Dict
from .integration_post_data import IntegrationPostData

def bot_telemetry_processor(data, context):
post_data = IntegrationPostData().activity_json
if post_data is None:
return
# Override session and user id
from_prop = post_data['from'] if 'from' in post_data else None
user_id = from_prop['id'] if from_prop != None else None
channel_id = post_data['channelId'] if 'channelId' in post_data else None
conversation = post_data['conversation'] if 'conversation' in post_data else None
conversation_id = conversation['id'] if 'id' in conversation else None
context.user.id = channel_id + user_id
context.session.id = conversation_id

# Additional bot-specific properties
if 'id' in post_data:
data.properties["activityId"] = post_data['id']
if 'channelId' in post_data:
data.properties["channelId"] = post_data['channelId']
if 'type' in post_data:
data.properties["activityType"] = post_data['type']


class ApplicationInsightsTelemetryClient(BotTelemetryClient):

def __init__(self, instrumentation_key:str):
def __init__(self, instrumentation_key:str, telemetry_client: TelemetryClient = None):
self._instrumentation_key = instrumentation_key
self._client = TelemetryClient(self._instrumentation_key)
self._client = telemetry_client if telemetry_client != None else TelemetryClient(self._instrumentation_key)
# Telemetry Processor
def telemetry_processor(data, context):
post_data = IntegrationPostData().activity_json
# Override session and user id
from_prop = post_data['from'] if 'from' in post_data else None
user_id = from_prop['id'] if from_prop != None else None
channel_id = post_data['channelId'] if 'channelId' in post_data else None
conversation = post_data['conversation'] if 'conversation' in post_data else None
conversation_id = conversation['id'] if 'id' in conversation else None
context.user.id = channel_id + user_id
context.session.id = conversation_id

# Additional bot-specific properties
if 'activityId' in post_data:
data.properties["activityId"] = post_data['activityId']
if 'channelId' in post_data:
data.properties["channelId"] = post_data['channelId']
if 'activityType' in post_data:
data.properties["activityType"] = post_data['activityType']

self._client.add_telemetry_processor(telemetry_processor)
self._client.add_telemetry_processor(bot_telemetry_processor)


def track_pageview(self, name: str, url:str, duration: int = 0, properties : Dict[str, object]=None,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from .bot_telemetry_middleware import BotTelemetryMiddleware, retrieve_bot_body

__all__ = [
"BotTelemetryMiddleware",
"retrieve_bot_body"
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import sys
import json
from threading import current_thread

# Map of thread id => POST body text
_request_bodies = {}

def retrieve_bot_body():
""" retrieve_bot_body
Retrieve the POST body text from temporary cache.
The POST body corresponds with the thread id and should resides in
cache just for lifetime of request.

TODO: Add cleanup job to kill orphans
"""
result = _request_bodies.pop(current_thread().ident, None)
return result

class BotTelemetryMiddleware():
"""
Save off the POST body to later populate bot properties
"""
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
self.process_request(request)
return self.get_response(request)

def process_request(self, request):
body_unicode = request.body.decode('utf-8') if request.method == "POST" else None
# Sanity check JSON
if body_unicode != None:
try:
body = json.loads(body_unicode)
except:
return
# Integration layer expecting just the json text.
_request_bodies[current_thread().ident] = body_unicode


Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import imp
import json
from botbuilder.schema import Activity
from botbuilder.applicationinsights.django import retrieve_bot_body

class IntegrationPostData:
"""
Expand Down Expand Up @@ -44,15 +45,8 @@ def get_request_body(self) -> str:
return body
else:
if self.detect_django():
mod = __import__('django.http', fromlist=['http'])
http_request = getattr(mod, 'HttpRequest')
django_requests = [o for o in gc.get_objects() if isinstance(o, http_request)]
django_request_instances = len(django_requests)
if django_request_instances != 1:
raise Exception(f'Detected {django_request_instances} instances of Django Requests. Expecting 1.')
request = django_requests[0]
body_unicode = request.body.decode('utf-8') if request.method == "POST" else None
return body_unicode
# Retrieve from Middleware cache
return retrieve_bot_body()

def body_from_WSGI_environ(self, environ):
try:
Expand Down
23 changes: 23 additions & 0 deletions libraries/botbuilder-applicationinsights/django_tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# DJANGO-specific tests
Django generates *code* to create projects (`django-admin startproject`) and apps. For testing, we test the generated code. The tests are bare-bones to be compatible across different versions of django.

- This project contains a script to execute tests against currently supported version(s) of python and django.
- Assume latest version of Application Insights.
- Relies on virtualenv to run all tests.
- Uses django commands to generate new project and execute django tests.
- To run, first `cd django_tests` and then `bash .\all_tests.sh` (ie, in Powershell) to run all permutations.

File | | Description
--- | ---
all_tests.sh | Runs our current test matrix of python/django versions. Current matrix is python (3.6) and django (2.2).
README.md | This file.
run_test.sh | Runs specific python/django version to create project, copy replacement files and runs tests.
template.html | Template file
tests.py | Django tests.
urls.py | url paths called by tests
views.py | paths that are called





58 changes: 58 additions & 0 deletions libraries/botbuilder-applicationinsights/django_tests/all_tests.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/bin/bash
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

if [ -z $PYTHON ]; then
PYTHON=$(which python)
fi

cd $(dirname $0)
BASEDIR=$(pwd)

# Django/python compatibility matrix...
if $PYTHON -c "import sys; sys.exit(1 if (sys.version_info.major == 3 and sys.version_info.minor == 6) else 0)"; then
echo "[Error] Environment should be configured with Python 3.6!" 1>&2
exit 2
fi
# Add more versions here (space delimited).
DJANGO_VERSIONS='2.2'

# For each Django version...
for v in $DJANGO_VERSIONS
do
echo ""
echo "***"
echo "*** Running tests for Django $v"
echo "***"
echo ""

# Create new directory
TMPDIR=$(mktemp -d)
function cleanup
{
rm -rf $TMPDIR
exit $1
}

trap cleanup EXIT SIGINT

# Create virtual environment
$PYTHON -m venv $TMPDIR/env

# Install Django version + application insights
. $TMPDIR/env/bin/activate
pip install Django==$v || exit $?
cd $BASEDIR/..
pip install . || exit $?

# Run tests
cd $BASEDIR
bash ./run_test.sh || exit $?

# Deactivate
# (Windows may complain since doesn't add deactivate to path properly)
deactivate

# Remove venv
rm -rf $TMPDIR
done
32 changes: 32 additions & 0 deletions libraries/botbuilder-applicationinsights/django_tests/run_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/bin/bash

# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

# It is expected at this point that django and applicationinsights are both installed into a
# virtualenv.
django_version=$(python -c "import django ; print('.'.join(map(str, django.VERSION[0:2])))")
test $? -eq 0 || exit 1

# Create a new temporary work directory
TMPDIR=$(mktemp -d)
SRCDIR=$(pwd)
function cleanup
{
cd $SRCDIR
rm -rf $TMPDIR
exit $1
}
trap cleanup EXIT SIGINT
cd $TMPDIR

# Set up Django project
django-admin startproject aitest
cd aitest
cp $SRCDIR/views.py aitest/views.py
cp $SRCDIR/tests.py aitest/tests.py
cp $SRCDIR/urls.py aitest/urls.py
cp $SRCDIR/template.html aitest/template.html

./manage.py test
exit $?
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Test django template: {{ context }}
Loading
0