Example #1
0
 def insert(self, *currency: Currency):
     if currency.__len__() == 1:
         self._db_connection.insert(self.collection(), currency[0].to_dict())
     elif currency.__len__() > 1:
         self._db_connection.insert_many(self.collection(),
                                         list(map(lambda this_currency: this_currency.to_dict(), currency)))
     else:
         print("CurrencyDao#insert: Nothing to insert")
Example #2
0
 def update(self, *currency: Currency):
     if currency.__len__() == 1:
         self._db_connection.update_one(self.collection(), {'currency_code': currency[0].currency_code},
                                        currency[0].to_dict())
     elif currency.__len__() > 1:
         for l_currency in currency:
             self.update(l_currency)
     else:
         print("CurrencyDao#update: Nothing to update")
Example #3
0
 def editCurrency(self,  currencyid,  currencyname,  abbreviation,  symbol ):
     """Edit currency 'currencyid' providing new name, abbreviation, symbol.
     """
     currency = Currency(currencyid)
     if not currency.name :
         raise CurrencyError(
             "Can't find Currency id %r which does not exist" % currencyid )
     currency.editData( currencyname,  abbreviation,  symbol )
     self.getCurrencies()    # update currency list
     return
Example #4
0
 def delete(self, *currency: Currency):
     if currency.__len__() == 1:
         self._db_connection.delete_one(self.collection(), {'currency_code': currency[0].currency_code})
     elif currency.__len__() > 1:
         self._db_connection.delete_many(self.collection(),
                                         {'currency_code': {
                                             "$set": list(map(lambda this_currency: this_currency.currency_code,
                                                              currency))}})
     else:
         print("CurrencyDao#delete: Nothing to delete")
Example #5
0
 def select_many(self, ftr: dict) -> [Currency]:
     return list(
         map(
             lambda obj: Currency(obj["currency_code"], obj["rate"], obj[
                 "historical_date"], obj["timestamp"], obj["friendly_name"]
                                  ),
             self.db_connection.select_many(self.collection, ftr)))
Example #6
0
    def setUp(self):
        self.logger = logging.getLogger()

        self.testFiles = []

        self.itemFile = Datafile('test.model.items.xml', self.id())
        self.itemFileAuctionOnly = Datafile('test.model.items.auction_only.xml', self.id())
        self.sessionFile = Datafile('test.model.session.xml', self.id())
        self.currencyFile = Datafile('test.model.currency.xml', self.id())
        self.importFileCsv = Datafile('test.model.import.csv', self.id())
        self.importFileTxt = Datafile('test.model.import.txt', self.id())

        self.dataset = Dataset(
                self.logger, './',
                self.sessionFile.getFilename(),
                self.itemFile.getFilename(),
                self.currencyFile.getFilename())
        self.dataset.restore()

        self.currency = Currency(
                self.logger,
                self.dataset,
                currencyCodes=['czk', 'eur'])
        self.model = Model(
                self.logger,
                self.dataset,
                self.currency)
Example #7
0
def getCurrencies():
    try:
        with open('data/currencies') as curfile:
            for line in curfile.readlines():
                row = line.split('\t')
                c = Currency(symbol=row[0], name=row[1].split('\n')[0])
                Cache.currencies[c.symbol] = c
    except Exception as ex:
        logging.error('here %s' % str(ex))
Example #8
0
    def setUp(self):
        self.logger = logging.getLogger()

        self.itemFile = Datafile('test.model.items.xml', self.id())
        self.sessionFile = Datafile('test.model.session.xml', self.id())
        self.currencyFile = Datafile('test.model.currency.xml', self.id())

        self.dataset = Dataset(
                self.logger, './',
                self.sessionFile.getFilename(),
                self.itemFile.getFilename(),
                self.currencyFile.getFilename())
        self.dataset.restore()

        self.currency = Currency(
                self.logger,
                self.dataset,
                currencyCodes=['czk', 'eur', 'usd'])
 def __init__(self):
     self.wd = WebDriver()
     self.wd.implicitly_wait(5)
     self.session = SessionHelper(self)
     self.payment = PaymentHelper(self)
     self.localization = LocalizationHelper(self)
     self.navigation = NavigationHelper(self)
     self.login_page = LoginPage(self)
     self.currency = Currency(self)
     self.payment_systems = PaymentSystems(self)
Example #10
0
def api(date):
    r = requests.get("http://www.cbr.ru/scripts/xml_daily.asp?date_req=%s" % date)
    root = ET.fromstring(r.text)
    list = []
    for Valute in root.findall('Valute'):
        num_code = Valute.find('NumCode').text
        char_code = Valute.find('CharCode').text
        nominal = Valute.find('Nominal').text
        name = Valute.find('Name').text
        value = Valute.find('Value').text
        list.append(Currency(numCode=num_code, charCode=char_code, nominal=nominal, name=name, value=value))
    return list
Example #11
0
 def extract_currency(self,amount):
     #currency= accounts.rub
     #cur_index=amount.find('RUB')
     #if cur_index<0:
     ##    cur_index=amount.find('USD')
     #   currency= accounts.usd
     #    if cur_index<0:
     #        cur_index=amount.find('EUR')
     #        currency= accounts.eur
     #        if cur_index<0:
     #            cur_index=amount.find('GBR')
     #            currency= accounts.gbr
     #            if cur_index<0:
     #                cur_index=amount.find('GBP')
     #                currency= accounts.gbr
     #                if cur_index<0:
     #                    raise Exception("Unknown currency in "+amount)
     currency, cur_index=Currency.str_to_currency_code(amount)
     return currency, cur_index
Example #12
0
 def get_curr(self, date):
     wd = self.app.wd
     self.app.open_currencies_page()
     self.set_date(date)
     list = []
     table = wd.find_element_by_xpath(".//*[@class='table']/table/tbody")
     for row in table.find_elements_by_tag_name("tr")[1:]:
         cells = row.find_elements_by_tag_name("td")
         num_code = cells[0].text
         char_code = cells[1].text
         nominal = cells[2].text
         name = cells[3].text
         value = cells[4].text
         list.append(
             Currency(numCode=num_code,
                      charCode=char_code,
                      nominal=nominal,
                      name=name,
                      value=value))
     return list
Example #13
0
 def _parse_xml_content(content: ElementTree) -> [Currency]:
     Logger.i(
         "CurrencyRepository#_parse_xml_content -> Beginning xml parsing")
     currency_list = []
     for item in content.iter():
         time = item.get("time")
         if time is not None:
             for currency_xml_obj in item:
                 currency = Currency()
                 currency_code = currency_xml_obj.get("currency")
                 rate = currency_xml_obj.get("rate")
                 if time is not None:
                     currency.historical_date = time
                 if currency_code is not None:
                     currency.currency_code = currency_code
                 if rate is not None:
                     currency.rate = float(rate)
                 currency.timestamp = datetime.datetime.timestamp(
                     datetime.datetime.now())
                 currency.friendly_name = currency_code
                 currency_list.append(currency)
     Logger.i(
         "CurrencyRepository#_parse_xml_content -> Xml parsing completed")
     return currency_list
Example #14
0
 def select_one(
         self,
         ftr: dict,
         sort_by: [list[tuple], tuple, str, None] = None) -> Currency:
     return Currency().from_dict(
         self.db_connection.select_one(self.collection, ftr, sort_by))
Example #15
0
app.root_path = ROOT_PATH
app.register_blueprint(items_controller.blueprint,
                       url_prefix=items_controller.URL_PREFIX)
app.register_blueprint(auction_controller.blueprint,
                       url_prefix=auction_controller.URL_PREFIX)
app.register_blueprint(reconciliation_controller.blueprint,
                       url_prefix=reconciliation_controller.URL_PREFIX)
app.register_blueprint(settings_controller.blueprint,
                       url_prefix=settings_controller.URL_PREFIX)
app.secret_key = config.SESSION_KEY

# Initialize application
dataset = Dataset(logging.getLogger('dataset'), config.DATA_FOLDER)
dataset.restore()
currency = Currency(logging.getLogger('currency'),
                    dataset,
                    currencyCodes=config.CURRENCY)
model = Model(logging.getLogger('model'), dataset, currency)
dictionaryPath = os.path.join(os.path.dirname(__file__), 'locale')
for language in config.LANGUAGES:
    registerDictionary(
        language,
        PhraseDictionary(
            logging.getLogger('dictionary'),
            os.path.join(dictionaryPath,
                         'translation.{0}.xml'.format(language))))
del dictionaryPath


@app.template_filter('reg_id_to_attendee')
def reg_id_to_attendee(s):
Example #16
0
from datetime import datetime

from model.currency import Currency
from repository.currency_repository import CurrencyRepository

mock_currency = Currency("USD", 1, "2020-01-01",
                         str(datetime.timestamp(datetime.now())),
                         "American Dolar")
currency_repository = CurrencyRepository()


def test_currency_insert():
    currency_repository.insert(mock_currency)
    currency_repository.delete(mock_currency)


def test_currency_select():
    currency_repository.insert(mock_currency)
    res = currency_repository.select_one(
        {'currency_code': mock_currency.currency_code})
    currency_repository.delete(mock_currency)
    assert isinstance(res, Currency)
Example #17
0
class TestCurrency(unittest.TestCase):
    def setUpClass():
        logging.basicConfig(level=logging.DEBUG)

    def setUp(self):
        self.logger = logging.getLogger()

        self.itemFile = Datafile('test.model.items.xml', self.id())
        self.sessionFile = Datafile('test.model.session.xml', self.id())
        self.currencyFile = Datafile('test.model.currency.xml', self.id())

        self.dataset = Dataset(
                self.logger, './',
                self.sessionFile.getFilename(),
                self.itemFile.getFilename(),
                self.currencyFile.getFilename())
        self.dataset.restore()

        self.currency = Currency(
                self.logger,
                self.dataset,
                currencyCodes=['czk', 'eur', 'usd'])

    def tearDown(self):
        self.itemFile.clear()
        self.sessionFile.clear()
        self.currencyFile.clear()

        del self.currency
        del self.dataset

        
    def test_convertToAllCurrencies(self):
        # Valid amount
        amountInCurrency = self.currency.convertToAllCurrencies(154)
        self.assertEqual(len(amountInCurrency), 3)
        self.assertEqual(amountInCurrency[0][CurrencyField.AMOUNT], Decimal('154'))
        self.assertEqual(amountInCurrency[1][CurrencyField.AMOUNT], Decimal('5.68'))
        self.assertEqual(amountInCurrency[2][CurrencyField.AMOUNT], Decimal('7.81'))

        # Valid negative amount
        amountInCurrency = self.currency.convertToAllCurrencies(-154)
        self.assertEqual(len(amountInCurrency), 3)
        self.assertEqual(amountInCurrency[0][CurrencyField.AMOUNT], Decimal('-154'))
        self.assertEqual(amountInCurrency[1][CurrencyField.AMOUNT], Decimal('-5.68'))
        self.assertEqual(amountInCurrency[2][CurrencyField.AMOUNT], Decimal('-7.81'))

        # Excessively large amount that would result to NaN
        amountInCurrency = self.currency.convertToAllCurrencies(Decimal('1E+30'))
        self.assertEqual(len(amountInCurrency), 3)
        self.assertEqual(amountInCurrency[0][CurrencyField.AMOUNT], Decimal('0'))
        self.assertEqual(amountInCurrency[1][CurrencyField.AMOUNT], Decimal('0'))
        self.assertEqual(amountInCurrency[2][CurrencyField.AMOUNT], Decimal('0'))

    def test_updateAmountWithAllCurrencies(self):
        item = {
                    'UNTOUCHABLE': 123,
                    'INPLACE': 100,
                    'OUTPLACE-SRC': 220 }
        self.currency.updateAmountWithAllCurrencies(item, {
                'INPLACE': 'INPLACE',
                'OUTPLACE-SRC': 'OUTPLACE-TGT',
                'UNDEFINED': 'UNDEFINED'})

        # Added fileds OUTPLACE-TGT and UNDEFINED
        self.assertEqual(len(item), 3 + 2)

        self.assertListEqual(item['UNDEFINED'], [])

        self.assertEqual(item['UNTOUCHABLE'], Decimal('123'))

        self.assertEqual(item['INPLACE'][0][CurrencyField.AMOUNT], Decimal('100'))
        self.assertEqual(item['INPLACE'][1][CurrencyField.AMOUNT], Decimal('3.69'))
        self.assertEqual(item['INPLACE'][2][CurrencyField.AMOUNT], Decimal('5.07'))

        self.assertEqual(item['OUTPLACE-SRC'], 220)
        self.assertEqual(item['OUTPLACE-TGT'][0][CurrencyField.AMOUNT], Decimal('220'))
        self.assertEqual(item['OUTPLACE-TGT'][1][CurrencyField.AMOUNT], Decimal('8.11'))
        self.assertEqual(item['OUTPLACE-TGT'][2][CurrencyField.AMOUNT], Decimal('11.16'))


    def test_roundInPrimary(self):
        # Conversion test
        self.assertEqual(self.currency.roundInPrimary('10.543'), Decimal('11'))
        self.assertEqual(self.currency.roundInPrimary(10.543), Decimal('11'))
        self.assertEqual(self.currency.roundInPrimary(Decimal('10.543')), Decimal('11'))
        self.assertEqual(self.currency.roundInPrimary(None), None)
        self.assertEqual(self.currency.roundInPrimary('NUMBER4'), None)

        # Position numbers
        self.assertEqual(self.currency.roundInPrimary(Decimal('10.541')), Decimal('11'))
        self.assertEqual(self.currency.roundInPrimary(Decimal('10.1')), Decimal('10'))
        self.assertEqual(self.currency.roundInPrimary(Decimal('19.995')), Decimal('20'))

        # Negative numbers
        self.assertEqual(self.currency.roundInPrimary(Decimal('-10.541')), Decimal('-11'))

        # Zero
        self.assertEqual(self.currency.roundInPrimary(Decimal('0.00')), Decimal('0'))