Changeset - 9d4723824592
[Not reviewed]
0 3 0
Brett Smith - 7 years ago 2017-05-16 16:26:32
brettcsmith@brettcsmith.org
rate: Add Rate.convert method.
3 files changed with 19 insertions and 2 deletions:
0 comments (0 inline, 0 general)
oxrlib/rate.py
Show inline comments
 
import datetime
 
import decimal
 
import functools
 
import json
 

	
 
class Rate:
 
    FIELDS = [
 
        'base',
...
 
@@ -31,17 +32,24 @@ class Rate:
 
        self.rates = rates
 

	
 
    @classmethod
 
    def deserialize_timestamp(cls, value):
 
        return datetime.datetime.fromtimestamp(value)
 

	
 
    @classmethod
 
    def serialize_rates(cls, rates):
 
        return {code: float(rates[code]) for code in rates}
 

	
 
    @classmethod
 
    def serialize_timestamp(cls, value):
 
        return int(value.timestamp())
 

	
 
    @classmethod
 
    def from_json_file(cls, json_file):
 
        response = json.load(json_file)
 
        response = json.load(json_file, parse_float=decimal.Decimal)
 
        return cls(**response)
 

	
 
    def convert(self, amount, from_currency, to_currency):
 
        return amount * self.rates[to_currency] / self.rates[from_currency]
 

	
 
    def serialize(self):
 
        return dict(self.walk_fields(functools.partial(getattr, self), 'serialize'))
tests/historical1.json
Show inline comments
...
 
@@ -3,9 +3,10 @@
 
    "license": "https://openexchangerates.org/license/",
 
    "timestamp": 982342800,
 
    "base": "USD",
 
    "rates": {
 
        "AED": 3.67246,
 
        "ALL": 144.529793,
 
        "ANG": 1.79
 
        "ANG": 1.79,
 
        "USD": 1
 
    }
 
}
tests/test_Rate.py
Show inline comments
 
import datetime
 
import decimal
 
import io
 
import json
 

	
 
from . import relpath
 

	
 
import oxrlib.rate
 
import pytest
 

	
 
HIST1_AED_RATE = decimal.Decimal('3.67246')
 
HIST1_ALL_RATE = decimal.Decimal('144.529793')
 

	
 
@pytest.fixture
 
def historical1_rate():
 
    with open(relpath('historical1.json').as_posix()) as rate_file:
 
        return oxrlib.rate.Rate.from_json_file(rate_file)
 

	
 
def test_rate_from_json(historical1_rate):
...
 
@@ -18,6 +22,10 @@ def test_rate_from_json(historical1_rate):
 

	
 
def test_serialize(historical1_rate):
 
    with open(relpath('historical1.json').as_posix()) as rate_file:
 
        expected = json.load(rate_file)
 
    assert expected == historical1_rate.serialize()
 

	
 
def test_convert(historical1_rate):
 
    assert historical1_rate.convert(2, 'USD', 'ALL') == (2 * HIST1_ALL_RATE)
 
    assert historical1_rate.convert(10, 'AED', 'USD') == (10 / HIST1_AED_RATE)
 
    assert historical1_rate.convert(1, 'AED', 'ALL') == (HIST1_ALL_RATE / HIST1_AED_RATE)
0 comments (0 inline, 0 general)