Skip to content

Commit

Permalink
remove config loading, instead pass auth details as dict
Browse files Browse the repository at this point in the history
  • Loading branch information
lukesmith committed Jul 15, 2015
1 parent 6d8e6e2 commit 917b504
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 70 deletions.
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@
# built documents.
#
# The short X.Y version.
version = '0.0.5'
version = open("hestia/_version.py").readlines()[-1].split()[-1].strip("\"'")
# The full version, including alpha/beta/rc tags.
release = '0.0.5'
release = open("hestia/_version.py").readlines()[-1].split()[-1].strip("\"'")

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand Down
1 change: 1 addition & 0 deletions hestia/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = '0.0.6'
46 changes: 19 additions & 27 deletions hestia/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,19 @@
import simplejson as json
import time
from six.moves.urllib.parse import urljoin
import six.moves.configparser as configparser
from sys import version_info


def load_configuration():
"""Load the configuration specified in /etc/hestia.conf."""
config = configparser.ConfigParser()
config_file = '/etc/hestia.conf'

if version_info.major == 2:
config.readfp(open(config_file))
else:
with open(config_file) as h:
config.read_string(h.read())
return config
from ._version import __version__ as hestia_version


class HestiaApi:
def __init__(self, settings):
"""Initialize a new instance of the HestiaApi.

Args:
settings: (configparser.ConfigParser): The settings to use.
__version__ = hestia_version

"""
def __init__(self, settings):
"""Initialize a new instance of the HestiaApi."""
self.__log = logging.getLogger("HestiaApi")
self.__settings = settings

def record_solar_river_reading(self, pv_output):
def record_solar_river_reading(self, installation_code, pv_output):
"""Record the readings from a Solar River inverter."""
payload = {
"date": str(pv_output.date_taken),
Expand All @@ -49,18 +33,17 @@ def record_solar_river_reading(self, pv_output):

self.__log.debug('Posting %s' % json.dumps(payload))
self.__post(
'photovoltaic/' + self.__settings.get('Photovoltaic',
'installation_code') + '/inverter/solar_river/readings',
'photovoltaic/%s/inverter/solar_river/readings' % installation_code,
json.dumps(payload),
{'content-type': 'application/json'})

def record_emon(self, data):
def record_emon(self, property_code, data):
"""Record the data from the EmonHub."""
sent_at = int(time.time())
data_string = json.dumps(data, separators=(',', ':'))
payload = "data=" + data_string + "&sentat=" + str(sent_at)

self.__post('property/' + self.__settings.get('Emon', 'property_code') + '/emon/readings', payload,
self.__post('property/%s/emon/readings' % property_code, payload,
{'content-type': 'application/x-www-form-urlencoded'})

def status(self):
Expand All @@ -70,6 +53,9 @@ def status(self):
def __post(self, path, payload, headers=None):
if not headers:
headers = {}

headers['User-Agent'] = 'Hestia Python API/%s' % HestiaApi.__version__

url = self.__remote_url(path)

self.__log.debug('Sending POST request to %s' % url)
Expand All @@ -84,6 +70,9 @@ def __post(self, path, payload, headers=None):
def __get(self, path, headers=None):
if not headers:
headers = {}

headers['User-Agent'] = 'Hestia Python API/%s' % HestiaApi.__version__

url = self.__remote_url(path)

self.__log.debug('Sending GET request to %s' % url)
Expand All @@ -95,7 +84,10 @@ def __get(self, path, headers=None):
return r.status_code

def __remote_url(self, path):
return urljoin(self.__settings.get('Remote', 'url'), path)
root = 'https://www.hestia.io'
if 'hestia_url' in self.__settings:
root = self.__settings['hestia_url']
return urljoin(root, path)

def __authentication(self):
return self.__settings.get('Remote', 'username'), self.__settings.get('Remote', 'password')
return self.__settings['username'], self.__settings['password']
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def read(fname):

setup(
name='hestia-api',
version='0.0.5',
version=open("hestia/_version.py").readlines()[-1].split()[-1].strip("\"'"),
description='Python library for accessing the hestia.io API',
author_email='info@hestia.io',
author='hestia.io',
Expand Down
51 changes: 11 additions & 40 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,88 +9,59 @@
from mock import patch
from mock import MagicMock

from helpers.utils import settings_from_string


class TestRecordSolarRiverInverterReading(unittest.TestCase):
def setUp(self):
config_file = """
[Remote]
url: https://test.hestia.io
username: username
password: password
[Photovoltaic]
installation_code: my_installation
"""
settings = settings_from_string(config_file)
self.api = HestiaApi(settings)
self.api = HestiaApi(dict(username='username', password='password'))

@httpretty.activate
def test_source_address(self):
httpretty.register_uri(httpretty.POST,
"https://test.hestia.io/photovoltaic/my_installation/inverter/solar_river/readings",
"https://www.hestia.io/photovoltaic/my_installation/inverter/solar_river/readings",
status=202,
content_type="application/json")

fake = MagicMock(date_taken=12345)
self.api.record_solar_river_reading(fake)
self.api.record_solar_river_reading('my_installation', fake)

assert httpretty.last_request().method == "POST"
assert httpretty.last_request().body.__len__() == 139
assert httpretty.last_request().headers['content-type'] == 'application/json'
assert httpretty.last_request().headers['user-agent'] == 'Hestia Python API/%s' % HestiaApi.__version__


class TestRecordEmonReading(unittest.TestCase):
def setUp(self):
config_file = """
[Remote]
url: https://test.hestia.io
username: username
password: password
[Emon]
property_code: my_property
"""
settings = settings_from_string(config_file)
self.api = HestiaApi(settings)
self.api = HestiaApi(dict(username='username', password='password'))

@httpretty.activate
def test_source_address(self):
httpretty.register_uri(httpretty.POST, "https://test.hestia.io/property/my_property/emon/readings",
httpretty.register_uri(httpretty.POST, "https://www.hestia.io/property/my_property/emon/readings",
status=202,
content_type="")

mock_time = MagicMock(return_value=1436377530)
with patch('time.time', mock_time):
self.api.record_emon([[123, 10, 345, 0, 0], [345, 10, 123, 0, 0]])
self.api.record_emon('my_property', [[123, 10, 345, 0, 0], [345, 10, 123, 0, 0]])

assert httpretty.last_request().method == "POST"
assert httpretty.last_request().body == b"data=[[123,10,345,0,0],[345,10,123,0,0]]&sentat=1436377530"
assert httpretty.last_request().headers['content-type'] == 'application/x-www-form-urlencoded'
assert httpretty.last_request().headers['user-agent'] == 'Hestia Python API/%s' % HestiaApi.__version__


class TestStatus(unittest.TestCase):
def setUp(self):
config_file = """
[Remote]
url: https://test.hestia.io
username: username
password: password
[Emon]
property_code: my_property
"""
settings = settings_from_string(config_file)
self.api = HestiaApi(settings)
self.api = HestiaApi(dict(username='username', password='password'))

@httpretty.activate
def test_source_address(self):
httpretty.register_uri(httpretty.GET, "https://test.hestia.io/status",
httpretty.register_uri(httpretty.GET, "https://www.hestia.io/status",
status=200,
content_type="application/json")

response = self.api.status()

assert response == 200
assert httpretty.last_request().method == "GET"
assert httpretty.last_request().headers['user-agent'] == 'Hestia Python API/%s' % HestiaApi.__version__
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ commands =
coveralls
deps =
-r{toxinidir}/dev-requirements.txt
-r{toxinidir}/requirements.txt
py27: mock==1.1.2

0 comments on commit 917b504

Please sign in to comment.