def test_conversion_rate_timeout(app, monkeypatch):
    def mock_requests_get_method(*args, **kwargs):
        raise requests.exceptions.ConnectTimeout("Connection Timeout")

    with app.app_context():
        monkeypatch.setattr("requests.get", mock_requests_get_method)
        with pytest.raises(requests.exceptions.ConnectTimeout):
            ConversionRate.get_conversion_rate("EUR", "PLN")
def test_update_conversion_rates_success(app, monkeypatch):

    new_allowed_currencies = ("USD", "EUR")
    expected_rates = {
        "USD_USD": 1.0,
        "USD_EUR": 0.84,
        "EUR_USD": 1.19,
        "EUR_EUR": 1.0
    }

    def new_get_conversion_rate(c1, c2):
        return expected_rates[f"{c1}_{c2}"]

    with app.app_context():

        monkeypatch.setattr(
            "currency_convertor.currency.models.allowed_currencies",
            new_allowed_currencies,
        )
        monkeypatch.setattr(
            "currency_convertor.currency.models.ConversionRate.get_conversion_rate",
            new_get_conversion_rate,
        )

        res = ConversionRate.update_conversion_rates()
        assert res["success"] == 1
        assert res["data"] == expected_rates

        # checking the database
        db_res = ConversionRate.query.filter_by(from_currency="EUR",
                                                to_currency="USD",
                                                latest=1).first()

        assert db_res.rate == Decimal(str(expected_rates["EUR_USD"]))
Ejemplo n.º 3
0
def init_db_command():
    """
    Clear existing data and create new tables.
    """
    init_db()
    from currency_convertor.currency.models import ConversionRate

    res = ConversionRate.update_conversion_rates()

    click.echo("Result of database update:")
    click.echo("-------------------------------------")
    click.echo(res)
    click.echo("Initialized the database.")
def test_conversion_rate_different_currencies(app, monkeypatch):
    class Response:
        status_code = 200

        def json(self):
            return {"EUR_PLN": 2.36}

    def mock_requests_get_method(*args, **kwargs):
        return Response()

    with app.app_context():
        monkeypatch.setattr("requests.get", mock_requests_get_method)
        assert ConversionRate.get_conversion_rate("EUR", "PLN") == 2.36
Ejemplo n.º 5
0
def convert(from_currency, to_currency, amount):
    """
    Main method in case of usage of conversion service.
    The format is:
    /convert/<string:from_currency>/<string:to_currency>/<amount>

    Parameters
    ----------
    from_currency : string
        The origin currency
    to_currency : string
        The destination currency
    amout : string
    """
    # check if the amount can be converted to float
    try:
        float(amount)
    except ValueError:
        return error("The amount has to be numeric", 400)

    # check if the currencies are one of the allowed
    if from_currency not in allowed_currencies:
        return error(
            "The origin currency {} is not found! Allowed currencies: {}".
            format(from_currency, ",".join(allowed_currencies)),
            400,
        )

    if to_currency not in allowed_currencies:
        return error(
            "The destination currency {} is not found! Allowed currencies: {}".
            format(to_currency, ",".join(allowed_currencies)),
            400,
        )

    # checking the in-memory cache for stored values that are not expired
    converted_amount = ConversionRate().convert_amount(from_currency,
                                                       to_currency, amount,
                                                       cache)

    if converted_amount:
        # we return the converted amount
        return {
            "from_currency": from_currency,
            "to_currency": to_currency,
            "amount": float(amount),
            "converted": float(converted_amount),
        }

    # This error will appear in case of an empty database
    return error("No exchange rate was found! Please try again later!", 500)
def test_convert_amount(app):

    with app.app_context():
        # case when the cache is empty; data is read from the database
        converted_amount = ConversionRate().convert_amount(
            "EUR", "USD", "1.234", cache)
        assert Decimal("1.472755554") == converted_amount

        # case when the cache is not empty; data is read from the cache
        converted_amount = ConversionRate().convert_amount(
            "EUR", "USD", "1.234", cache)
        assert Decimal("1.472755554") == converted_amount

        # case when there is no conversipon rate in the database, neither in cache; None is reaturned
        ConversionRate.query.filter_by(from_currency="EUR",
                                       to_currency="USD",
                                       latest=1).delete()
        db.session.commit()
        cache.invalidate_all()

        converted_amount = ConversionRate().convert_amount(
            "EUR", "USD", "1.234", cache)
        assert converted_amount is None
def test_update_conversion_rates_fail(app, monkeypatch):
    new_allowed_currencies = ("USD", "EUR")
    expected_rates = {
        "USD_USD": 1.0,
        "USD_EUR": 0.33,
        "EUR_USD": 1.77,
        "EUR_EUR": 1.0
    }

    def new_get_conversion_rate(c1, c2):

        if not (c1 == "EUR" and c2 == "EUR"):
            return expected_rates[f"{c1}_{c2}"]
        else:
            raise requests.exceptions.ConnectionError(
                "Connection Error Mock HAHAHA")

    with app.app_context():
        # checking the database
        db_res_before = ConversionRate.query.filter_by(from_currency="EUR",
                                                       to_currency="USD",
                                                       latest=1).first()

        monkeypatch.setattr(
            "currency_convertor.currency.models.allowed_currencies",
            new_allowed_currencies,
        )
        monkeypatch.setattr(
            "currency_convertor.currency.models.ConversionRate.get_conversion_rate",
            new_get_conversion_rate,
        )

        res = ConversionRate.update_conversion_rates()

        assert res["success"] == 0
        assert res["data"] == {
            "USD_USD": 1.0,
            "USD_EUR": 0.33,
            "EUR_USD": 1.77
        }
        assert "error" in res

        # checking the database didn't change
        db_res_after = ConversionRate.query.filter_by(from_currency="EUR",
                                                      to_currency="USD",
                                                      latest=1).first()

        assert db_res_before.rate == db_res_after.rate
Ejemplo n.º 8
0
def update():
    return ConversionRate.update_conversion_rates()
def test_financial_multiplication(a, b, result):
    assert ConversionRate.financial_multiplication(a, b) == result
def test_no_cache_convert_amount(app):
    with app.app_context():
        # case when the cache is empty; data is read from the database
        converted_amount = ConversionRate().convert_amount(
            "EUR", "USD", "1.234")
        assert Decimal("1.472755554") == converted_amount
def test_conversion_rate_equal_currencies():
    res = ConversionRate.get_conversion_rate("USD", "USD")
    assert res == 1.0