Python code for currency converter

Following code fetches currency conversion rates from the Internet and then converts currencies. First you need to install the forex-python library

!pip install forex-python

Code to fetch rates and convert currencies

from forex_python.converter import CurrencyRates

# Initialize the CurrencyRates object
cr = CurrencyRates()

# Fetch exchange rates for a specific currency
rates = cr.get_rates('USD')
print(rates)

# Convert currency
amount = 100
from_currency = "USD"
to_currency = "INR"
converted_amount = cr.convert(from_currency, to_currency, amount)
print(f"{amount} {from_currency} = {converted_amount} {to_currency}")

This code uses the forex-python library to fetch the exchange rates and convert the currency. The get_rates function returns a dictionary of exchange rates for a specific currency, and the convert function takes the source currency, target currency, and the amount as input and returns the converted amount.

Unit Test

import unittest
from forex_python.converter import CurrencyRates

class TestCurrencyConversion(unittest.TestCase):
    def setUp(self):
        self.cr = CurrencyRates()
        self.from_currency = "USD"
        self.to_currency = "INR"
        self.amount = 100

    def test_fetch_rates(self):
        rates = self.cr.get_rates(self.from_currency)
        self.assertIsInstance(rates, dict)
        self.assertIn(self.to_currency, rates)
    
    def test_currency_conversion(self):
        converted_amount = self.cr.convert(self.from_currency, self.to_currency, self.amount)
        self.assertIsInstance(converted_amount, float)

if __name__ == '__main__':
    unittest.main()

This code uses the unittest library to write unit tests for the get_rates and convert functions. The TestCurrencyConversion class defines the tests and uses the setUp method to initialize the necessary objects and variables. The test_fetch_rates test checks if the exchange rates are fetched correctly and the test_currency_conversion test checks if the currency conversion is done correctly.