Skip to content

Commit

Permalink
Improve coverage + fix example
Browse files Browse the repository at this point in the history
  • Loading branch information
bargenson committed May 26, 2017
1 parent e56a353 commit 730c5bb
Show file tree
Hide file tree
Showing 8 changed files with 134 additions and 84 deletions.
26 changes: 14 additions & 12 deletions barracks_sdk/barracks_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def get_device_packages(self, device_info):
verify = not self._allow_self_signed
)
if response.status_code == 200:
print response.json()
return self._convert_to_packages(response.json())
else:
raise BarracksRequestException(response.request.body, response.text)
Expand All @@ -47,7 +48,7 @@ def _convert_to_packages(self, json_response):
return {
'availablePackages': list(map(lambda item: self._build_downloadable_package(item), json_response['available'])),
'changedPackages': list(map(lambda item: self._build_downloadable_package(item), json_response['changed'])),
'unchangedPackages': list(map(lambda item: self._buildPackage(item), json_response['unchanged'])),
'unchangedPackages': list(map(lambda item: self._build_package(item), json_response['unchanged'])),
'unavailableReferences': list(map(lambda item: item['reference'], json_response['unavailable']))
}

Expand All @@ -62,7 +63,7 @@ def _build_downloadable_package(self, dictionary):
self.download_package
)

def _buildPackage(self, dictionary):
def _build_package(self, dictionary):
return Package(
dictionary['reference'],
dictionary['version']
Expand All @@ -79,16 +80,17 @@ def download_package(self, package, destination = None):
stream = True
)
if response.status_code == 200:
hash_md5 = hashlib.md5()
with open(destination, 'wb') as f:
for chunk in response.iter_content(1024):
f.write(chunk)
hash_md5.update(chunk)
if hash_md5.hexdigest() == package._md5:
return PackageFile(destination, package)
else:
os.remove(destination)
raise BarracksChecksumException(package)
self._create_file_and_verify_checksum(response, destination, package._md5)
return PackageFile(destination, package)
else:
raise BarracksDownloadException(response.request.body, response.text)

def _create_file_and_verify_checksum(self, http_response, destination, checksum):
hash_md5 = hashlib.md5()
with open(destination, 'wb') as f:
for chunk in http_response.iter_content(1024):
f.write(chunk)
hash_md5.update(chunk)
if hash_md5.hexdigest() != checksum:
os.remove(destination)
raise BarracksChecksumException(hash_md5.hexdigest(), checksum)
4 changes: 2 additions & 2 deletions barracks_sdk/checksum_exception.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class BarracksChecksumException(Exception):

def __init__(self, package):
super(BarracksChecksumException, self).__init__('Checksum verification failed for package %s' % (package.reference))
def __init__(self, calculatedChecksum, expectedChecksum):
super(BarracksChecksumException, self).__init__('Checksum verification failed: found=%s, expected %s' % (calculatedChecksum, expectedChecksum))
3 changes: 3 additions & 0 deletions barracks_sdk/package_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ class PackageFile:
def __init__(self, file_path, package):
self.file_path = file_path
self.package = package

def __eq__(self, other):
return self.__dict__ == other.__dict__
20 changes: 14 additions & 6 deletions example/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,35 @@
import sys
import imp

from barracks_sdk import BarracksUpdater, DeviceInfo, BarracksRequestException, BarracksDownloadException, BarracksChecksumException
from barracks_sdk import *

def main():
parser = argparse.ArgumentParser(
description='This is an implementation example of the BarracksUpdater.'
)
group = parser.add_argument_group('authentication')
group.add_argument('-a', '--api_key', help='Your Barracks API key')
group.add_argument('-u', '--unit_id', help='The unit ID')
group.add_argument('-k', '--api_key', help='Your Barracks API key')

args = parser.parse_args()

api_key = args.api_key
unit_id = args.unit_id

if api_key is None:
print('client.py -a <your_api_key>')
if api_key is None or unit_id is None:
print('client.py -u <unit_id> -k <your_api_key>')
sys.exit(2)
else:
# Let's initialise the SDK with the API key and the base URL
try:
updater = BarracksUpdater(api_key, 'https://barracks.ddns.net', True)
packages = updater.get_device_packages(DeviceInfo('unitId', []))
updater = BarracksUpdater(api_key)
packages = updater.get_device_packages(
DeviceInfo(
unit_id,
[ Package('io.barracks.app1', '0.0.1') ],
{ "prop1": "Value 1" }
)
)
print 'Barracks response: ', packages
downloadAndInstallPackages(packages['availablePackages'])
downloadAndInstallPackages(packages['changedPackages'])
Expand Down
109 changes: 86 additions & 23 deletions tests/barracks_sdk/barracks_updater_test.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from barracks_sdk import *
import unittest
from mock import patch, Mock
from mock import patch, Mock, ANY, MagicMock, mock_open
import hashlib
from package_utils import build_package, build_downloadable_package
import uuid
import json
import requests_mock
from barracks_sdk import BarracksUpdater, DeviceInfo, JsonSerializer, BarracksRequestException, DownloadablePackage, Package

class BarrackUpdaterTest(unittest.TestCase):

Expand All @@ -13,6 +14,13 @@ class BarrackUpdaterTest(unittest.TestCase):
api_key = 'qwertyuiop'
unit_id = 'my_unit'
json_serializer_mock = Mock()
file_content = """
GYUGUYFUY67867tGGUYGFYTF676t76gfHGFVYFYTF6768t7TGUGFFYFYr76r7tguyghjgvYRO
&^^&gfvugf76tr7GJVGU&&^Tfguvuy76rtuyGVJGU&T&^ghjvuyt76fhvuyF&^TUYGUYT&UGV
JVUYFUYVJUF&^fuyfg7fhvFU&^RUYFU&rUG*ugbvjhbvGVUYFG&^76fghjvytfd6E^YTFCVY5
HGI&*YIUhbhjg78tgyiugBI*T&giygutyd456eDYFVJKNBJCXsterd6yufygjvhhcytDY&FYt
GYUT^&Gjgfty5665rftyvgTSEVTdtryftugjuHGUYTE^dDFYTJHGCVFYJTykugi76UYKFVKYT
"""

def test__constructor__when__only_api_key(self):
# When
Expand Down Expand Up @@ -58,6 +66,11 @@ def test__get_device_packages__should__post_device_info_and_return_packages(self
convert_to_package_mock.return_value = { 'availablePackages': list() }
requests.post(
self.default_base_url + '/api/device/resolve',
headers={
'Authorization': self.api_key,
'Content-type': 'application/json',
'Accept': 'application/json'
},
additional_matcher=lambda request: serialize_mock.return_value in (request.text or ''),
json=api_response
)
Expand All @@ -81,6 +94,11 @@ def test__get_device_packages__should__raise_an_exception__when__http_request_fa
serialize_mock.return_value = '{"aJson":"withValue"}'
requests.post(
self.default_base_url + '/api/device/resolve',
headers={
'Authorization': self.api_key,
'Content-type': 'application/json',
'Accept': 'application/json'
},
additional_matcher=lambda request: serialize_mock.return_value in (request.text or ''),
status_code=400
)
Expand Down Expand Up @@ -237,30 +255,75 @@ def test__convert_to_packages__should__transform_unavailable_references_in_json_
self.assertFalse(result['changedPackages'])
self.assertFalse(result['unchangedPackages'])

###############
# # When
# headers = barracks_updater._BarracksUpdater__get_headers()
@requests_mock.mock()
@patch.object(BarracksUpdater, '_create_file_and_verify_checksum')
def test__download_package__should__return_PackageFile__when__download_request_and_checksum_are_successful(self, requests, create_file_mock):
# Given
destination = '/tmp/plop'
package = build_downloadable_package(Mock())
expectedResult = PackageFile(destination, package)
response = requests.get(
package._url,
status_code=200,
headers={ 'Authorization': self.api_key },
text=self.file_content
)

# When
barracks_updater = BarracksUpdater(self.api_key)
result = barracks_updater.download_package(package, destination)

# Then
self.assertEquals(result, expectedResult)
create_file_mock.assert_called_once_with(ANY, destination, package._md5)

@requests_mock.mock()
@patch.object(BarracksUpdater, '_create_file_and_verify_checksum')
def test__download_package__should__raise_exception__when__http_request_is_not_successful(self, requests, create_file_mock):
# Given
destination = '/tmp/plop'
package = build_downloadable_package(Mock())
expectedResult = PackageFile(destination, package)
response = requests.get(
package._url,
status_code=401,
headers={ 'Authorization': self.api_key }
)

# # Then
# self.assertEquals(headers, expected)
# When # Then
barracks_updater = BarracksUpdater(self.api_key)
with self.assertRaises(BarracksDownloadException):
barracks_updater.download_package(package, destination)

# def test__build_payload_when_no_package_in_device_info(self):
# # Given
# barracks_updater = BarracksUpdater(api_key)
# device_info = DeviceInfo(unit_id, [])
# expected = {
# 'unitId': unit_id,
# 'components': []
# }
# Then
create_file_mock.assert_not_called()

# # When
# payload = barracks_updater._BarracksUpdater__build_payload(device_info)
@patch('__builtin__.open', new_callable=mock_open())
def test__create_file_and_verify_checksum__should__create_file__when_checksum_is_valid(self, open_mock):
# Given
response_content = '123'
http_response = Mock()
http_response.iter_content = Mock(return_value=iter([response_content]))
destination = '/tmp/plop'
checksum = hashlib.md5(response_content).hexdigest()

# # Then
# self.assertEquals(payload, expected)
# When
barracks_updater = BarracksUpdater(self.api_key)
barracks_updater._create_file_and_verify_checksum(http_response, destination, checksum)

# def test__build_payload_when_packages_in_device_info(self):
# self.assertTrue(False)
# Then
open_mock.assert_called_once_with(destination, 'wb')

def test__create_file_and_verify_checksum__should__raise_an_exception__when_checksum_is_invalid(self):
# Given
response_content = '123'
http_response = Mock()
http_response.iter_content = Mock(return_value=iter([response_content]))
destination = '/tmp/plop'
checksum = 'BaDch3Cksum'

# When # Then
barracks_updater = BarracksUpdater(self.api_key)
with self.assertRaises(BarracksChecksumException):
barracks_updater._create_file_and_verify_checksum(http_response, destination, checksum)

# def test__build_payload_when_packages_and_custom_client_data_in_device_info(self):
# self.assertTrue(False)
27 changes: 0 additions & 27 deletions tests/barracks_sdk/downloadable_package_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,3 @@ def test__download__should__call_the_received_callback(self):
# Then
self.assertEquals(result, expected_result)
callback.assert_called_once_with(package, location)


# reference = 'io.barracks.app';
# version = '1.2.3';
# url = 'https://app.barracks.io/path/to/package/version',
# filename = 'setup.sh'
# size = 9876543
# md5 = 'uhgvcfdszsewe67ygvhuioijnkl'

# def test_downloadable_package_constructor():
# """
# Tests that the Package class exposes reference and version property
# """
# package = DownloadablePackage(reference, version, url, filename, size, md5)
# assert isinstance(package, Package)
# assert isinstance(package, DownloadablePackage)
# assert package.reference == reference
# assert package.version == version
# assert package.url == url
# assert package.filename == filename
# assert package.size == size
# assert package.md5 == md5

# def test_download():
# # package = DownloadablePackage(reference, version, url, filename, size, md5)
# # package.download()
# assert True
2 changes: 1 addition & 1 deletion tests/barracks_sdk/package_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ def build_downloadable_package(download_callback):
return DownloadablePackage(
str(uuid.uuid1()),
str(uuid.uuid1()),
str(uuid.uuid1()),
'https://' + str(uuid.uuid1()),
str(uuid.uuid1()),
1337,
str(uuid.uuid1()),
Expand Down
27 changes: 14 additions & 13 deletions tests/barracks_sdk/test_package.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# from barracks_sdk import Package

# reference = 'io.barracks.app';
# version = '1.2.3';

# def test_package_constructor():
# """
# Tests that the Package class exposes reference and version property
# """
# package = Package(reference, version)
# assert isinstance(package, Package)
# assert package.reference == reference
# assert package.version == version
[
{
"reference": "greg.pckg.test",
"version": "0.2.0"
},
{
"reference": "com.test.1234",
"version": "v-1490894199"
},
{
"reference": "ref-package-1490294068",
"version": "coucou"
}
]

0 comments on commit 730c5bb

Please sign in to comment.