I'm using a custom templatetag to calculate currency values, currency is chosen from a select element. when the user choose the currency he want work with I save the chosen currency in the session and refresh the page.
a templatetag shows the value calculated for the choosen currency.
in any template
{% load currency %}
{% set_currency request 156 %}
in my_app/templatetags/currency.py
from django.conf import settings
from djmoney_rates.utils import convert_money
register = template.Library()
@register.inclusion_tag('includes/price.html')
def set_currency(request, price):
# currency_session could be 'USD', 'EUR' ...
currency_session = request.session.get(settings.CURRENCY_SESSION_KEY, settings.DEFAULT_CURRENCY)
money = convert_money(price, settings.DEFAULT_CURRENCY, currency_session)
return {'amount': '%d' % money.amount, 'currency': money.currency}
includes/price.html is just
<span class="amount">{{amount}}</span>
<span class="currency">{{currency}}</span>
Now I'm wondering the way to test this templatetag, how to pass the request, and how make session to exists in that request.
I would only test the function.
from django.test import TestCase, RequestFactory
from django.conf import settings
from my_app.templatetags.currency import set_currency
class SetCurrencyTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_set_currency(self):
request = self.factory.get('/any/path/really/')
request.session = {
settings.CURRENCY_SESSION_KEY: settings.DEFAULT_CURRENCY
}
response = set_currency(request, 156)
self.assertEqual(response['amount'], 42)
self.assertEqual(response['currency'], 'BTC')
I'd also consider setting request.session
without using settings
, but that depends on your application.