Skip to content
Snippets Groups Projects
Commit d812e386 authored by Ruben.Havre's avatar Ruben.Havre
Browse files

Merge branch 'testing' into 'master'

Added lots of tests. And fixed some issues with the client, discovered while testing

See merge request !4
parents 18c2e717 feeab4ce
No related branches found
No related tags found
1 merge request!4Added lots of tests. And fixed some issues with the client, discovered while testing
Pipeline #51419 passed
...@@ -47,3 +47,15 @@ transactions = [Transaction.from_dict({ ...@@ -47,3 +47,15 @@ transactions = [Transaction.from_dict({
multi = Multi(batch=batch, vouchers=vouchers, transactions=transactions) multi = Multi(batch=batch, vouchers=vouchers, transactions=transactions)
response = c.post_multi(multi) response = c.post_multi(multi)
``` ```
Running tests
-------------
```
pytest
```
or
```
python3 setup.py test
```
"""Client for connecting to SETRA API""" """Client for connecting to SETRA API"""
import json import json
import logging import logging
import os
import urllib.parse import urllib.parse
from typing import Tuple, Union, List from typing import Tuple, Union, List
...@@ -12,16 +11,6 @@ from setra_client.models import Multi ...@@ -12,16 +11,6 @@ from setra_client.models import Multi
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def load_json_file(name):
"""Load json file from the fixtures directory"""
here = os.path.realpath(
os.path.join(os.getcwd(),
os.path.dirname(__file__).rsplit('/', 1)[0]))
with open(os.path.join(here, 'tests/fixtures', name)) as f:
data = json.load(f)
return data
def merge_dicts(*dicts): def merge_dicts(*dicts):
""" """
Combine a series of dicts without mutating any of them. Combine a series of dicts without mutating any of them.
...@@ -158,7 +147,7 @@ class SetraClient(object): ...@@ -158,7 +147,7 @@ class SetraClient(object):
if return_response: if return_response:
return r return r
r.raise_for_status() r.raise_for_status()
return r.json() return r.json() # Note: krasjer her, dersom man får text og ikke json i requesten, og return_response=false
def get(self, url, **kwargs): def get(self, url, **kwargs):
return self.call('GET', url, **kwargs) return self.call('GET', url, **kwargs)
...@@ -178,23 +167,33 @@ class SetraClient(object): ...@@ -178,23 +167,33 @@ class SetraClient(object):
""" """
GETs one or all batches from SETRA GETs one or all batches from SETRA
""" """
url = self.urls.batch(str(batch_id)) if batch_id is not None:
batch_id = str(batch_id)
url = self.urls.batch(batch_id)
response = self.get(url) response = self.get(url)
return response.json() return response.json()
def get_voucher(self, vouch_id: int): def get_voucher(self, vouch_id: int = None):
""" """
GETs one or all batches from SETRA GETs one or all vouchers from SETRA
""" """
url = self.urls.voucher(str(vouch_id)) if vouch_id is not None:
vouch_id = str(vouch_id)
url = self.urls.voucher(vouch_id)
response = self.get(url) response = self.get(url)
return response.json() return response.json()
def get_transaction(self, trans_id: int): def get_transaction(self, trans_id: int = None):
""" """
GETs one or all batches from SETRA GETs one or all transactions from SETRA
""" """
url = self.urls.transaction(str(trans_id)) if trans_id is not None:
trans_id = str(trans_id)
url = self.urls.transaction(trans_id)
response = self.get(url) response = self.get(url)
return response.json() return response.json()
......
import json import json
import pytest import pytest
import requests_mock import requests
import os
from setra_client.client import SetraClient, SetraEndpoints, load_json_file from setra_client.client import SetraClient, SetraEndpoints
def load_json_file(name):
"""Load json file from the fixtures directory"""
here = os.path.realpath(
os.path.join(os.getcwd(),
os.path.dirname(__file__).rsplit('/', 1)[0]))
with open(os.path.join(here, 'tests/fixtures', name)) as f:
data = json.load(f)
return data
@pytest.fixture @pytest.fixture
...@@ -31,6 +42,16 @@ def client(baseurl): ...@@ -31,6 +42,16 @@ def client(baseurl):
return SetraClient(baseurl) return SetraClient(baseurl)
@pytest.fixture
def client_with_a_header(baseurl):
return SetraClient(baseurl, {"content-type": "test"})
@pytest.fixture
def batch_url(baseurl):
return SetraEndpoints(baseurl).batch() # https://localhost/api/batch
@pytest.fixture @pytest.fixture
def batch_fixture(): def batch_fixture():
return load_json_file('batch_fixture.json') return load_json_file('batch_fixture.json')
......
import pytest import pytest
import requests
from requests import HTTPError from requests import HTTPError
from setra_client.client import SetraEndpoints
from setra_client.client import SetraClient from setra_client.client import SetraClient
from json.decoder import JSONDecodeError
from setra_client.models import Multi
@pytest.fixture @pytest.fixture
...@@ -41,10 +44,238 @@ def test_init_modify_defaults(client_cls, baseurl, header_name): ...@@ -41,10 +44,238 @@ def test_init_modify_defaults(client_cls, baseurl, header_name):
# Check that we don't do this by mutating default_headers # Check that we don't do this by mutating default_headers
assert client.default_headers[header_name] != headers[header_name] assert client.default_headers[header_name] != headers[header_name]
#
# def test_get_update_schema(client, requests_mock): # Test call method
# """Ensure getting update schema works"""
# requests_mock.get('https://localhost/_webservices/?ws=contacts/upsert/1.0', def test_get_successful_batch_with_json_content(client, requests_mock, baseurl):
# json={'foo': 'bar'}) """A working GET call should return HTTP 200, with json content"""
# response = client.get_update_schema()
# assert response == {'foo': 'bar'} url = SetraEndpoints(baseurl).batch(batch_id='3') # https://localhost/api/batch/3
requests_mock.get(url, json={'foo': 'bar'}, status_code=200)
response = client.call(method_name='GET', url=url)
assert response.status_code == 200
assert response.json() == {'foo': 'bar'}
def test_get_successful_batch_with_text_content(client, requests_mock, baseurl):
"""A working GET call should return HTTP 200, with json content"""
url = SetraEndpoints(baseurl).batch(batch_id='3') # https://localhost/api/batch/3
requests_mock.get(url, text="some content", status_code=200)
response = client.call(method_name='GET', url=url)
assert response.status_code == 200
assert response.text == "some content"
def test_get_failing_batch_with_json_content(client, batch_url, requests_mock, baseurl):
"""A failing GET call with 404 should pass through the same response from the client, and return HTTP 404,
and the request with json content"""
requests_mock.get(batch_url, json={'a': 'b'}, status_code=404)
resp = client.call(method_name='GET', url=batch_url)
assert resp.status_code == 404
assert resp.json() == {'a': 'b'}
def test_get_failing_batch_with_text_content(client, batch_url, requests_mock, baseurl):
"""A failing GET call with 404 should pass through the same response from the client, and return HTTP 404,
and the request with json content"""
requests_mock.get(batch_url, text="some content", status_code=404)
resp = client.call(method_name='GET', url=batch_url)
assert resp.status_code == 404
assert resp.text == "some content"
def test_get_failing_batch_without_return_response_text(client, batch_url, requests_mock, baseurl):
"""A failing GET call with 404 should raise HTTPError from the client,
and return HTTP 404, and the request with text content"""
requests_mock.get(batch_url, text="some content", status_code=404)
with pytest.raises(HTTPError) as err:
client.call(method_name='GET', url=batch_url, return_response=False)
assert err.type == requests.exceptions.HTTPError
assert err.value.response.status_code == 404
assert err.value.response.text == "some content"
def test_get_failing_batch_without_return_response_json(client, batch_url, requests_mock, baseurl):
"""A failing GET call with 404 should raise HTTPError from the client,
and return HTTP 404, and the request with json content"""
requests_mock.get(batch_url, json={'a': 'b'}, status_code=404)
with pytest.raises(HTTPError) as err:
client.call(method_name='GET', url=batch_url, return_response=False)
assert err.type == requests.exceptions.HTTPError
assert err.value.response.status_code == 404
assert err.value.response.json() == {'a': 'b'}
def test_get_failing_batch_without_return_response2(client, batch_url, requests_mock, baseurl):
"""A failing GET call with 404 returning text content, with return_response=False
should raise for HTTPError from the client
(because we expect json from setra, and it will give error with text content) """
requests_mock.get(batch_url, text="some content", status_code=200)
with pytest.raises(JSONDecodeError) as err:
client.call(method_name='GET', url=batch_url, return_response=False)
assert err.type == JSONDecodeError
# Test post method
def test_get_failing_batch_with_http500(client, batch_url, requests_mock, baseurl):
"""A failing POST call with return_response=False and http 500,
should raise HTTPError from the client,
and return HTTP 500, and the request with json content"""
requests_mock.post(batch_url, json={'a': 'b'}, status_code=500)
with pytest.raises(HTTPError) as err:
client.post(url=batch_url, return_response=False)
assert err.type == requests.exceptions.HTTPError
assert err.value.response.status_code == 500
assert err.value.response.json() == {'a': 'b'}
def test_get_failing_batch_with_http5002(client, batch_url, requests_mock, baseurl):
"""A failing POST call with 500 with return_response=True,
should just return the response, with 500"""
requests_mock.post(batch_url, json={'a': 'b'}, status_code=500)
response = client.post(url=batch_url)
assert response.status_code == 500
assert response.json() == {'a': 'b'}
# Test setting headers
def test_header_replacement(client_with_a_header, batch_url, requests_mock, baseurl):
"""Given a SetraClient created with a "global" header,
making a request with the same header key,
should replace the "global" header value"""
requests_mock.get(batch_url, text="some content", status_code=200, headers={"content-type": "replaced"})
response = client_with_a_header.call(method_name='GET', url=batch_url, headers={"content-type": "replaced"})
assert response.status_code == 200
assert response.text == "some content"
assert response.headers == {"content-type": "replaced"}
def test_header_replacement2(client_with_a_header, batch_url, requests_mock, baseurl):
"""Given a SetraClient created with a "global" header,
making a request with the same header key,
should replace the "global" header value,
while new headers should be added to the request"""
requests_mock.get(batch_url, text="some content", status_code=200, headers={"content-type": "replaced", "key": "val"})
response = client_with_a_header.call(method_name='GET', url=batch_url, headers={"content-type": "replaced"})
assert response.status_code == 200
assert response.text == "some content"
assert response.headers == {"content-type": "replaced", "key": "val"}
# Test get_batches method
def test_successful_get_all_batches(client, requests_mock, baseurl):
"""A working GET call should return HTTP 200, with json content"""
url = SetraEndpoints(baseurl).batch()
requests_mock.get(url, json={'foo': 'bar'}, status_code=200)
response = client.get_batch()
assert response == {'foo': 'bar'}
def test_successfully_getting_single_batch(client, requests_mock, baseurl):
"""A working GET call should return HTTP 200, with json content"""
url = SetraEndpoints(baseurl).batch(batch_id='3')
requests_mock.get(url, json={'foo': 'bar'}, status_code=200)
response = client.get_batch(3)
assert response == {'foo': 'bar'}
def test_failing_to_get_all_batches(client, batch_url, requests_mock, baseurl):
"""A failing GET batches call should still return json"""
requests_mock.get(batch_url, json={'error': 'some json error message'}, status_code=404)
response = client.get_batch()
assert response == {'error': 'some json error message'}
def test_failing_to_get_all_batches_with_text(client, batch_url, requests_mock, baseurl):
"""A failing GET batches call that return text instead of json,
will raise JSONDecodeError in setra client"""
requests_mock.get(batch_url, text='some json error message', status_code=404)
with pytest.raises(JSONDecodeError):
client.get_batch()
# Test get_voucher method
def test_successfully_getting_single_voucher(client, requests_mock, baseurl):
"""A working GET call should return HTTP 200, with json content"""
url = SetraEndpoints(baseurl).voucher(vouch_id='5')
requests_mock.get(url, json={'foo': 'bar'}, status_code=200)
response = client.get_voucher(5)
assert response == {'foo': 'bar'}
def test_failing_to_get_all_vouchers(client, requests_mock, baseurl):
"""A failing GET all vouchers call should still return json"""
url = SetraEndpoints(baseurl).voucher()
requests_mock.get(url, json={'error': 'some json error message'}, status_code=404)
response = client.get_voucher()
assert response == {'error': 'some json error message'}
# Test get_transaction method
def test_successfully_getting_single_transaction(client, requests_mock, baseurl):
"""A working GET call should return HTTP 200, with json content"""
url = SetraEndpoints(baseurl).transaction(trans_id='9')
requests_mock.get(url, json={'foo': 'bar'}, status_code=200)
response = client.get_transaction(9)
assert response == {'foo': 'bar'}
def test_failing_to_get_all_transactions(client, requests_mock, baseurl):
"""A failing GET all vouchers call should still return json"""
url = SetraEndpoints(baseurl).transaction()
requests_mock.get(url, json={'error': 'some json error message'}, status_code=404)
response = client.get_transaction()
assert response == {'error': 'some json error message'}
# Test post_multi method
def test_successfully_post_multi(client, multi_fixture, requests_mock, baseurl):
"""A working GET call should return HTTP 200, with json content"""
url = SetraEndpoints(baseurl).post_multi()
multi = Multi.from_dict(multi_fixture)
requests_mock.post(url, json={'somestatus': 'ok'}, status_code=200, request_headers={"Content-Type": "application/json"})
response = client.post_multi(multi) # we only get json back
assert response == {'somestatus': 'ok'}
def test_successfully_post_multi_with_response(client, multi_fixture, requests_mock, baseurl):
"""A working POST multi call with return_response=True,
should return the response with HTTP 200, with json content"""
url = SetraEndpoints(baseurl).post_multi()
requests_mock.post(url, json={'somestatus': 'ok'}, status_code=200, request_headers={"Content-Type": "application/json"}) #expect json content
multi = Multi.from_dict(multi_fixture)
response = client.post_multi(multi, return_response=True) # we get a response back
assert response.json() == {'somestatus': 'ok'}
assert response.status_code == 200
...@@ -6,3 +6,31 @@ def test_init(baseurl): ...@@ -6,3 +6,31 @@ def test_init(baseurl):
assert endpoints.baseurl == baseurl assert endpoints.baseurl == baseurl
def test_init_batchurl(baseurl):
endpoints = SetraEndpoints(baseurl)
assert endpoints.batch_url == "api/batch/"
# Test urls:
def test_init_batch_with_value(baseurl):
endpoints = SetraEndpoints(baseurl)
assert endpoints.batch(batch_id="5") == baseurl + "/api/batch/5"
def test_init_batch_with_empty_value(baseurl):
endpoints = SetraEndpoints(baseurl)
assert endpoints.batch(batch_id="") == baseurl + "/api/batch/"
def test_init_batch_without_value(baseurl):
endpoints = SetraEndpoints(baseurl)
assert endpoints.batch() == baseurl + "/api/batch/"
def test_init_transaction_with_value(baseurl):
endpoints = SetraEndpoints(baseurl)
assert endpoints.transaction(trans_id="5") == baseurl + "/api/transaction/5"
def test_init_transaction_without_value(baseurl):
endpoints = SetraEndpoints(baseurl)
assert endpoints.transaction() == baseurl + "/api/transaction/"
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment