def currency_converter(): amount = request.args.get("amount") input_currency = request.args.get("input_currency") output_currency = request.args.get("output_currency") # amount and input_currency are required if amount is None or input_currency is None: abort(400) # amount has to be valid float try: amount = float(amount) except ValueError: abort(400) c = CurrencyConverter() # handle errors from conversion try: output = c.convert(amount, input_currency, output_currency) except (HTTPError, ConnectionError): abort(503) # server error, API unavailable except KeyError: abort(400) # client error, invalud currency code return jsonify(output)
def test_conversionRateChangesAndIsReloaded(self, mockGetLatestRatesFromFixerIO): #In this test we are going to make some calls, then arrange for the rate to expire and a new one to be loaded # we will then make some more calls and check we get expected results responses = [] responses.append(getLatestRatesFromFixerIO_Response_RateOf4) responses.append(getLatestRatesFromFixerIO_Response_RateOf2) mockGetLatestRatesFromFixerIO.side_effect = responses #Set a time in the appObj to initiate testing mode (Will stop any chance of expiry during the test) curDateTime = appObj.getCurDateTime() appObj.setTestingDateTime(curDateTime) converterInstance = CurrencyConverter(appObj, apikey) #call the code under test a number of times before the cache expiry numberOfCallsToMake = 4 for c in range(0, numberOfCallsToMake): self.assertEqual(converterInstance.convertFromGBPtoUSD(testAmounts['GBP']), testAmounts['USD4'], "Incorrect currency conversion result") #go forward 30 mintues - the rate should have changed because the cache will be invalidated appObj.setTestingDateTime(curDateTime + converterInstance.rateRefreshInterval + relativedelta(minutes=30)) #call the code under test a number of times after the cache expiry (new result) for c in range(0, numberOfCallsToMake): self.assertEqual(converterInstance.convertFromGBPtoUSD(testAmounts['GBP']), testAmounts['USD2'], "Incorrect currency conversion result") #Make sure there were two calls to the mock, one before the cache expiry and one after self.assertEqual(mockGetLatestRatesFromFixerIO.call_args_list,[call(apikey),call(apikey)],"Wrong calls to API") return
def convert_in(self, to_currenty: str): try: el = CurrencyConverter() return Ccy(round( el.convert(self.currency, to_currenty.upper(), self.suma), 2), to_currenty) except KeyError as e: print(e)
def all(self, other, operation): try: if str(other).isdigit(): return operation(self.suma, other) else: el = CurrencyConverter() new_suma = el.convert(other.currency, self.currency, other.suma) return operation(self.suma, new_suma) except KeyError as e: print(e)
def test_singleConversionDifferentRate(self, mockGetLatestRatesFromFixerIO): #Setup mock to return a rate of 4 mockGetLatestRatesFromFixerIO.side_effect = [ getLatestRatesFromFixerIO_Response_RateOf4, ] converterInstance = CurrencyConverter(appObj, apikey) self.assertEqual(converterInstance.convertFromGBPtoUSD(testAmounts['GBP']), testAmounts['USD4'], "Incorrect currency conversion result") #Make sure there was only one call and it had the correct APIKEY self.assertEqual(mockGetLatestRatesFromFixerIO.call_args_list,[call(apikey)],"Wrong calls to API") return
def init(self, env, serverStartTime, testingMode=False): self.curDateTimeOverrideForTesting = None self.serverStartTime = serverStartTime self.version = readFromEnviroment(env, 'APIAPP_VERSION', None, None) apikey = readFromEnviroment(env, 'APIAPP_FIXERIO_APIKEY', None, None) self.currencyConverter = CurrencyConverter(self, apikey) super(appObjClass, self).init(env)
def test_conversionRateIsCachedBetweenCalls(self, mockGetLatestRatesFromFixerIO): numberOfCallsToMake = 4 #setup mock object - setting up a number of responses even though we should only use the first one responses = [] for c in range(0, numberOfCallsToMake): responses.append(getLatestRatesFromFixerIO_Response_RateOf4) mockGetLatestRatesFromFixerIO.side_effect = responses #Set a time in the appObj to initiate testing mode (Will stop any chance of expiry during the test) curDateTime = appObj.getCurDateTime() appObj.setTestingDateTime(curDateTime) #call code under test converterInstance = CurrencyConverter(appObj, apikey) for c in range(0, numberOfCallsToMake): self.assertEqual(converterInstance.convertFromGBPtoUSD(testAmounts['GBP']), testAmounts['USD4'], "Incorrect currency conversion result") #Make sure there was only one call with the correct APIKEY self.assertEqual(mockGetLatestRatesFromFixerIO.call_args_list,[call(apikey)],"Wrong calls to API") return
def init(self): base.BaseApplet.init(self, needsversion="4.5") if self.hasFailedToLaunch(): return KGlobal.locale().insertCatalog(self.metadata.pluginName()) lang = KGlobal.locale().language() print "Language:", lang print "Translated?", KGlobal.locale().isApplicationTranslatedInto(lang) self._widget = None self.dialog = None self.has_tooltip = False self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.notifier = Notifier(self) self.nwmon = NetworkMonitor() if self.nwmon.connected(): self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self.nwmon.status_changed.connect(self.netstate_changed) # Main widget print("CurrencyConverterApplet: Creating main widget.") self._widget = CurrencyConverter(self) self._widget.init() self.setGraphicsWidget(self._widget) self.setPopupIcon(self.metadata.pluginName()) self.setGraphicsWidget(self._widget) #self.setup_tooltip() self.configChanged() self._widget.updated.connect(self.setup_tooltip)
from ExtractorURL import ExtractorURL from CurrencyConverter import CurrencyConverter #"bytebank.com/cambio?quantity=100&origin=real&target=euro" url = input('Informe a URL: ') extractor_url = ExtractorURL(url) origin = extractor_url.params['origin'] target = extractor_url.params['target'] quantity = float(extractor_url.params['quantity']) currency_converter = CurrencyConverter(origin, target, quantity) print(currency_converter)
class CurrencyConverterApplet(base.BaseApplet): def __init__(self,parent,args=None): base.BaseApplet.__init__(self,parent) def init(self): base.BaseApplet.init(self, needsversion="4.5") if self.hasFailedToLaunch(): return KGlobal.locale().insertCatalog(self.metadata.pluginName()) lang = KGlobal.locale().language() print "Language:", lang print "Translated?", KGlobal.locale().isApplicationTranslatedInto(lang) self._widget = None self.dialog = None self.has_tooltip = False self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.notifier = Notifier(self) self.nwmon = NetworkMonitor() if self.nwmon.connected(): self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self.nwmon.status_changed.connect(self.netstate_changed) # Main widget print("CurrencyConverterApplet: Creating main widget.") self._widget = CurrencyConverter(self) self._widget.init() self.setGraphicsWidget(self._widget) self.setPopupIcon(self.metadata.pluginName()) self.setGraphicsWidget(self._widget) #self.setup_tooltip() self.configChanged() self._widget.updated.connect(self.setup_tooltip) def createConfigurationInterface(self, dialog): self.ui = CurrencyConverterConfig(self.dialog) p = dialog.addPage(self.ui, i18n("General") ) p.setIcon( KIcon("currency-converter") ) #self.notify_widget = KCModuleProxy("kcmnotify", dialog, ["currency-converter",]) #real_module = self.notify_widget.realModule() ##print "Module:", real_module #p = dialog.addPage(self.notify_widget, i18n("Notifications") ) #p.setIcon( KIcon("dialog-information") ) dialog.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel | KDialog.Apply))) dialog.showButton(KDialog.Apply, False) #self.connect(dialog, SIGNAL("applyClicked()"), self, SLOT("configAccepted()")) #self.connect(dialog, SIGNAL("okClicked()"), self, SLOT("configAccepted()")) dialog.applyClicked.connect(self.configAccepted) dialog.okClicked.connect(self.configAccepted) self.ui.update_interval.setValue(self._widget.update_interval) #@pyqtSignature("configAccepted()") @pyqtSlot(name="configAccepted") def configAccepted(self): print "CurrencyConverterApplet::configAccepted" self._widget.update_interval = self.ui.update_interval.value() self.cfg.writeEntry("update_interval", QVariant(self._widget.update_interval)) self.constraintsEvent(Plasma.SizeConstraint) self.update() self._widget.start_timer() self.emit(SIGNAL("configNeedsSaving()")) #self.configNeedsSaving.emit() def contextualActions(self): # Add custom context menus print "CurrencyConverterApplet::contextualActions" actions = [] ac_update = QAction(KIcon("view-refresh"), i18n("Update now"), self) #checkNow = QAction(KIcon(self.package().path() + "contents/icons/check.svg"), "Check email now", self) #self.connect(ac_update, SIGNAL("triggered()"), self._widget.do_convert) if hasattr(self, '_widget') and self._widget is not None: ac_update.triggered.connect(self._widget.do_convert) actions.append(ac_update) print actions return actions # Never called..? def updateToolTipContent(self): print "CurrencyConverterApplet::updateToolTipContent" @QtCore.pyqtSlot(name="setup_tooltip") def setup_tooltip(self): print "setup_tooltip: Last updated:", self._widget.lastUpdated() # Tool tip for panel if self.has_tooltip: Plasma.ToolTipManager.self().clearContent(self.applet) self.metadata = self.package().metadata() self.tooltipdata = Plasma.ToolTipContent() self.tooltipdata.setAutohide(False) self.tooltipdata.setMainText(self.metadata.name()) #self.tooltipdata.setSubText(self.metadata.description()) tooltip_txt = str(i18nc("From code From Amount = To code To Amount - Last updated", "%s %s = %s %s<br /><br />Last updated:<br />%s")) tooltip_txt= tooltip_txt % (self._widget.fromCurrency(), self._widget.fromAmount(), self._widget.toCurrency(), self._widget.toAmount(), self._widget.lastUpdated()) #print tooltip_txt self.tooltipdata.setSubText(tooltip_txt) self.tooltipdata.setImage(KIcon(self.metadata.pluginName())) Plasma.ToolTipManager.self().setContent(self.applet, self.tooltipdata) # Only register the tooltip in panels #if (self.formFactor() != Plasma.Planar): if ((self.formFactor() == Plasma.Horizontal) or (self.formFactor() == Plasma.Vertical)): #print("CurrencyConverterApplet: In Panel") Plasma.ToolTipManager.self().registerWidget(self.applet) self.has_tooltip = True else: Plasma.ToolTipManager.self().clearContent(self.applet) Plasma.ToolTipManager.self().unregisterWidget(self.applet) #print("CurrencyConverterApplet: Not in Panel") self.has_tooltip = False def configChanged(self): print("CurrencyConverterApplet: configChanged") # TODO: # Clear ComboBoxes # Add currencies # Select currencies # Convert @QtCore.pyqtSlot(bool, name="netstate_changed") def netstate_changed(self, connected): print "CurrencyConverterApplet: Network status changed!", connected if connected: print("CurrencyConverterApplet: Connected!") self._widget.setEnabled(True) self._widget.start_timer() self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self._widget.setEnabled(False) print("CurrencyConverterApplet: Not connected!") self.setBusy(True) # Whys isn't this called? @QtCore.pyqtSlot(name="toolTipAboutToShow") def toolTipAboutToShow(self): print "CurrencyConverterApplet:toolTipAboutToShow"
parser.add_argument( "--amount", help="Enter amount to convert", type=float, required=True ) parser.add_argument( "--input_currency", help="Enter 3-letter code or symbol of currency, which you want to convert from", type=str, required=True, ) parser.add_argument( "--output_currency", help="Enter 3-letter code or symbol of currency, which you want to convert to (if not specified, converts to all available currencies)", type=str, ) args = parser.parse_args() c = CurrencyConverter() try: output_json = json.dumps( c.convert(args.amount, args.input_currency, args.output_currency) ) except (HTTPError, ConnectionError): output_json = json.dumps( {"error": "Currency API is not available at this time."} ) except KeyError as err: output_json = json.dumps({"error": f"{err} is not a valid currency code."}) print(output_json)
from CurrencyConverter import CurrencyConverter from Currency import * rates = {'USD': 1.0, 'EUR': 0.5, 'JAP': 2} currency_converter = CurrencyConverter(rates) def test_converter_same(): assert currency_converter.convert(Currency(1, 'USD'), 'USD') == Currency(1, 'USD') def test_converter_different(): assert currency_converter.convert(Currency(1, 'USD'), 'EUR') == Currency(0.5, "EUR") test_converter_same() test_converter_different()
def test_mult_values(): a = Currency('USD', 8) c = 5 assert a * c == Currency('USD', 40) def test_single_arg(): a = Currency('$8') b = Currency('USD', 8) assert a == b # create a new currencyconverter object with the rates you'll be using converter = CurrencyConverter({'USD': 1, 'GBP': 0.82, 'EUR': 0.91}) def test_currency_code_same(): a = Currency('USD', 8) assert converter.convert(a, 'USD') == Currency('USD', 8) def test_currency_code_dif(): a = Currency('USD', 2) assert converter.convert(a, 'GBP') == Currency('GBP', 1.64) @raises(UnknownCurrencyCodeError) def test_unknown_currency(): a = Currency('USD', 1)