Skip to content

Commit

Permalink
Merge pull request #9 from journy-io/small-tweaks
Browse files Browse the repository at this point in the history
Add bugfixes for HttpClientRequests and adding of events
  • Loading branch information
ManuDeBuck authored Feb 16, 2021
2 parents 1cb03f1 + b00b585 commit ed09dac
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 84 deletions.
52 changes: 26 additions & 26 deletions .github/workflows/lint-and-test.yml
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
name: Lint code and run tests
on: push
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
matrix:
python-version: [ 3.6, 3.7, 3.8 ]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
pytest
build:
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
matrix:
python-version: [ 3.6, 3.7, 3.8 ]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
pytest
52 changes: 26 additions & 26 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
name: Upload Python Package

on:
release:
types: [ created ]
release:
types: [ created ]

jobs:
deploy:
deploy:

runs-on: ubuntu-latest
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Get the version
id: get_version
run: echo ::set-output name=tag::${GITHUB_REF/refs\/tags\//}
- name: Update version to tag
run: python scripts/setversion.py setup.py "${{ steps.get_version.outputs.tag }}"
- name: Build package
run: python setup.py sdist bdist_wheel
- name: Publish distribution 📦to PyPI
uses: pypa/gh-action-pypi-publish@master
with:
user: __token__
password: ${{ secrets.PYPI_TOKEN }}
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Get the version
id: get_version
run: echo ::set-output name=tag::${GITHUB_REF/refs\/tags\//}
- name: Update version to tag
run: python scripts/setversion.py setup.py "${{ steps.get_version.outputs.tag }}"
- name: Build package
run: python setup.py sdist bdist_wheel
- name: Publish distribution 📦to PyPI
uses: pypa/gh-action-pypi-publish@master
with:
user: __token__
password: ${{ secrets.PYPI_TOKEN }}
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ This is the official Python SDK for [journy.io](https://journy.io?utm_source=git
You can use the python package manager (`pip`) to install the SDK:

```bash
pip install journyio
pip install journyio-sdk
```

## 🔌 Getting started
Expand All @@ -21,7 +21,7 @@ pip install journyio
To start, first import the client.

```pyhton
from journyio import Client, Config
from journyio.client import Client, Config
```

### Configuration
Expand All @@ -37,7 +37,7 @@ Go to your settings, under the *Connections*-tab, to create and edit API keys. M
to the API Key.

```python
from journyio import HttpClientRequests
from journyio.httpclient import HttpClientRequests

config = Config("api-key-secret")
http_client = HttpClientRequests() # If wanted, an own implementation of the HttpClient interface can be created
Expand All @@ -49,7 +49,7 @@ client = Client(http_client, config)
#### Get API key details

```python
from journyio import Success
from journyio.results import Success

result = client.get_api_key_details()
if isinstance(result, Success):
Expand All @@ -64,7 +64,7 @@ if isinstance(result, Success):
_Note: when sending an empty value (`""`) as value for a property, the property will be deleted._

```python
from journyio import Properties
from journyio.client import Properties

properties = Properties()
properties["property1"] = "value1"
Expand Down Expand Up @@ -131,7 +131,7 @@ def method(request):

```python
from datetime import datetime
from journyio import Event, Metadata
from journyio.events import Event, Metadata

metadata = Metadata()
metadata["metadata1"] = "value1"
Expand All @@ -149,7 +149,7 @@ if isinstance(result, Success):
#### Get tracking snippet for a domain

```python
from journyio import Success
from journyio.results import Success

result = client.get_tracking_snippet("www.journy.io")
if isinstance(result, Success):
Expand All @@ -168,7 +168,7 @@ many requests, not found...). Our SDK only throws `JournyExceptions`, no other e
called. `JournyExceptions` are provided with useful messages, which state where the error was made.

```python
from journyio import JournyException
from journyio.utils import JournyException

try:
result = client.get_tracking_snippet("www.journy.io")
Expand Down
22 changes: 13 additions & 9 deletions journyio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,17 +98,21 @@ def add_event(self, event: Event) -> Success[None] or Failure:
assert_journy(isinstance(event, Event), "The event should be an Event object.")

try:
body = {
"identification": {},
"name": event.name,
"metadata": event.metadata.metadata
}
if event.date:
body["triggeredAt"] = event.date.isoformat()
if event.user_id:
body["identification"]["userId"] = event.user_id
if event.account_id:
body["identification"]["accountId"] = event.account_id

request = HttpRequest(self.__create_url("/events"), Method.POST,
self.__get_headers(),
json.dumps({
"identification": {
"userId": event.user_id,
"accountId": event.account_id
},
"name": event.name,
"triggeredAt": event.date.isoformat() if event.date else None,
"metadata": event.metadata.metadata
}))
json.dumps(body))
response = self.httpclient.send(request)
calls_remaining = Client.__parse_calls_remaining(response)
if not (200 <= response.status_code < 300):
Expand Down
6 changes: 3 additions & 3 deletions journyio/httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,11 @@ def send(self, request: HttpRequest):
if not method:
raise JournyException("No correct method was given.")
try:
response = method(request.url, headers=request.headers, data=request.body)
response = method(request.url, headers=request.headers.headers, data=request.body)
headers = HttpHeaders()
for header in response.headers:
headers[header] = response.headers[header]
return HttpResponse(response.status_code, headers, response.text)
return HttpResponse(response.status_code, headers, json.loads(response.text))
except:
raise JournyException("An unknown error has occurred while performing the API request.")

Expand Down Expand Up @@ -152,4 +152,4 @@ def __str__(self):
return f"HttpClientTesting({self.dummy_response}, {self.received_request})"

def __repr__(self):
return self.__str__()
return self.__str__()
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
long_description = fh.read()

setuptools.setup(
name="journyio",
name="journyio-sdk",
version="0.0.1",
author="journy.io",
author_email="hi@journy.io",
Expand Down
21 changes: 11 additions & 10 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import datetime

import pytest

from journyio.client import Config, Properties, Client
from journyio.events import Event, Metadata
from journyio.httpclient import HttpClientTesting, HttpResponse, HttpHeaders
Expand Down Expand Up @@ -52,7 +53,7 @@ def test_client():
assert (client.httpclient.__str__() == http_client_testing.__str__())
assert (client.config.__str__() == config.__str__())
assert (
client.__str__() == "Client(HttpClientTesting(HttpResponse(200, {}, None), None), Config(api-key, https://api.journy.io))")
client.__str__() == "Client(HttpClientTesting(HttpResponse(200, {}, None), None), Config(api-key, https://api.journy.io))")


rate_limit_header = HttpHeaders()
Expand Down Expand Up @@ -97,7 +98,7 @@ def test_client_add_event():
assert (response.data is None)

assert (
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/events, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"identification": {"userId": "user_id", "accountId": "account_id"}, "name": "login", "triggeredAt": "2020-11-02T13:37:40", "metadata": {"true": true, "key": "value"}})')
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/events, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"identification": {"userId": "user_id", "accountId": "account_id"}, "name": "login", "metadata": {"true": true, "key": "value"}, "triggeredAt": "2020-11-02T13:37:40"})')


def test_client_add_event_with_failure():
Expand All @@ -114,7 +115,7 @@ def test_client_add_event_with_failure():
assert (response.error is APIError.TooManyRequests)

assert (
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/events, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"identification": {"userId": "user_id", "accountId": "account_id"}, "name": "login", "triggeredAt": "2020-11-02T13:37:40", "metadata": {"true": true, "key": "value"}})')
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/events, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"identification": {"userId": "user_id", "accountId": "account_id"}, "name": "login", "metadata": {"true": true, "key": "value"}, "triggeredAt": "2020-11-02T13:37:40"})')


def test_client_upsert_user():
Expand All @@ -136,7 +137,7 @@ def test_client_upsert_user():
assert (response.data is None)

assert (
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/users/upsert, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"email": "manu@journy.io", "userId": "userId", "properties": {"hasdog": false, "name": "Manu"}})')
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/users/upsert, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"email": "manu@journy.io", "userId": "userId", "properties": {"hasdog": false, "name": "Manu"}})')


def test_client_upsert_account():
Expand All @@ -158,7 +159,7 @@ def test_client_upsert_account():
assert (response.data is None)

assert (
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/accounts/upsert, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"accountId": "accountId", "name": "journy", "properties": {"havedog": false, "name": "Journy"}, "members": ["hansId", "manuId"]})')
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/accounts/upsert, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"accountId": "accountId", "name": "journy", "properties": {"havedog": false, "name": "Journy"}, "members": ["hansId", "manuId"]})')


def test_client_link():
Expand All @@ -176,7 +177,7 @@ def test_client_link():
assert (response.data is None)

assert (
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/link, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"deviceId": "device_id", "userId": "user_id"})')
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/link, Method.POST, {"content-type": "application/json", "x-api-key": "api-key"}, {"deviceId": "device_id", "userId": "user_id"})')


def test_client_get_tracking_snippet():
Expand All @@ -189,13 +190,13 @@ def test_client_get_tracking_snippet():

assert (isinstance(response, Success))
assert (
response.__str__() == "Success(requestId, 4999, TrackingSnippetResponse(journy.io, <script>snippet</script>))")
response.__str__() == "Success(requestId, 4999, TrackingSnippetResponse(journy.io, <script>snippet</script>))")
assert (response.calls_remaining == 4999)
assert (response.request_id == "requestId")
assert (isinstance(response.data, TrackingSnippetResponse))

assert (
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/tracking/snippet?domain=journy.io, Method.GET, {"content-type": "application/json", "x-api-key": "api-key"}, None)')
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/tracking/snippet?domain=journy.io, Method.GET, {"content-type": "application/json", "x-api-key": "api-key"}, None)')


def test_client_get_api_key_details():
Expand All @@ -208,10 +209,10 @@ def test_client_get_api_key_details():

assert (isinstance(response, Success))
assert (
response.__str__() == "Success(requestId, 4999, ApiKeyDetails(['TrackData', 'GetTrackingSnippet', 'ReadUserProfile']))")
response.__str__() == "Success(requestId, 4999, ApiKeyDetails(['TrackData', 'GetTrackingSnippet', 'ReadUserProfile']))")
assert (response.calls_remaining == 4999)
assert (response.request_id == "requestId")
assert (isinstance(response.data, ApiKeyDetails))

assert (
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/validate, Method.GET, {"content-type": "application/json", "x-api-key": "api-key"}, None)')
http_client_testing.received_request.__str__() == 'HttpRequest(https://api.journy.io/validate, Method.GET, {"content-type": "application/json", "x-api-key": "api-key"}, None)')
3 changes: 2 additions & 1 deletion tests/test_events.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime

import pytest

from journyio.events import Metadata, Event
Expand Down Expand Up @@ -42,7 +43,7 @@ def test_event():
assert (event_2.__str__() == "Event(logout, user_id, None, 2020-11-02 13:37:50, {})")
assert (event_3.__str__() == "Event(login, None, account_id, 2020-11-02 13:37:40, {})")
assert (
event_4.__str__() == 'Event(login, user_id, account_id, 2020-11-02 13:37:50, {"true": true, "key": "value"})')
event_4.__str__() == 'Event(login, user_id, account_id, 2020-11-02 13:37:50, {"true": true, "key": "value"})')

with pytest.raises(JournyException):
Event(None, None, None, None, Metadata())
Expand Down

0 comments on commit ed09dac

Please sign in to comment.