def setUpTestData(cls): # Create admin user from different source cls.bob_credentials = [ 'admin_bob', '*****@*****.**', "7u35ITpAss" ] cls.root_credentials = [ 'admin_root', '*****@*****.**', "7u35ITpAss" ] cls.create_admins() # Login the users cls.c_admin_root = cls.login_client(cls.root_credentials) cls.c_admin_bob = cls.login_client(cls.bob_credentials) # Create records Userdata.objects.create(owner=cls.user_bob, first_name='Alice', last_name='Doe', iban=IBAN.generate( country_code='DE', bank_code='37040044', account_code='0532013000').formatted) Userdata.objects.create(owner=cls.user_root, first_name='Bob', last_name='Bob', iban=IBAN.generate( country_code='DE', bank_code='37040044', account_code='0532013000').formatted)
def main(): d = dateparser.parse('2.Mai 2020', languages=['de']) print(d) d = dateparser.parse('2.Abc 2020', languages=['de']) print(d) d = dateparser.parse('2020.12.8') print(d) print() p = Price.fromstring("-114,47 €") print(p) p = Price.fromstring("3 500 руб") print(p) p = Price.fromstring("Rs. 11,499") print(p) p = Price.fromstring("$1499.99") print(p) p = Price.fromstring("199,999.00") print(p) p = Price.fromstring("199.999,00") print(p) print() i = IBAN('LT12 1000 0111 0100 1000') print(i.country) i = IBAN('DE89 3704 0044 0532 0130 00') print(i.country) try: i = IBAN('DE89 3704') print(i.country) except Exception as e: print(e)
def test_magic_methods(): iban = IBAN('DE42430609677000534100') assert iban == 'DE42430609677000534100' assert iban == IBAN('DE42430609677000534100') assert iban != IBAN('ES9121000418450200051332') assert iban < IBAN('ES9121000418450200051332') assert str(iban) == 'DE42430609677000534100' assert repr(iban) == '<IBAN=DE42430609677000534100>'
def test_magic_methods(): iban = IBAN("DE42430609677000534100") assert iban == "DE42430609677000534100" assert iban == IBAN("DE42430609677000534100") assert iban != IBAN("ES9121000418450200051332") assert iban < IBAN("ES9121000418450200051332") assert str(iban) == "DE42430609677000534100" assert hash(iban) == hash("DE42430609677000534100") assert repr(iban) == "<IBAN=DE42430609677000534100>"
def guess_bank(self): pool = Pool() Bank = pool.get('bank') if IBAN and self.iban: iban = IBAN(self.iban) if iban.bic: return Bank.from_bic(iban.bic)
def clean_iban(self): if self.data['iban'] != '': try: iban = IBAN(self.data['iban']) except ValueError: raise ValidationError(_('IBAN ist nicht gültig')) return self.data['iban']
def preprocess_post(**kw): submitter = kw['data']['submitter'] iban = kw['data']['iban'] description = kw['data']['description'] receipts = kw['data']['receipts'] kw['data']['date'] = str(datetime.now()) errors = [] if len(submitter or '\0') == 0: errors.append('Nimi on pakollinen kenttä.') try: IBAN(iban or '\0') except ValueError: errors.append('IBAN ei ole validi.') if len(description or '\0') == 0: errors.append('Maksun peruste tulee antaa.') if len(receipts) == 0: errors.append('Tositteita ei löytynyt.') if len(errors) > 0: raise ProcessingException(description='\n'.join(errors)) for r in receipts: Receipt.check(**r) nrs = [] for r in receipts: nrs.append(Receipt.preprocess(**r)) kw['data']['receipts'] = nrs
def find(iban=None, bank_code=None): """Find FinTS URL for a german bank. Keyword arguments: iban -- a valid german IBAN (overrides bank_code) bank_code -- a valid german bank code (fallback if iban not provided) """ if iban: iban = IBAN(iban) if not isinstance(iban, IBAN) else iban if iban.country_code != 'DE': raise Exception("FinTS is supported by german banks only!") bank_code = iban.bank_code if not bank_code: raise Exception("Please provide IBAN or bank code!") try: url = __bank_info__[str(bank_code)]['fints'] except: raise Exception("FinTS URL not found for %s" % str(bank_code)) log.debug("FinTS URL for IBAN=%s bank_code=%s: %s" % (iban, bank_code, url)) return url
def withdrawal_eur(request): try: sum_eur = dec(request.POST['sum_eur'], DECIMAL_PLACES_EUR) except ValueError: return withdrawal(request, error_message='Nesprávna hodnota', active='eur') iban = request.POST['account_number'] try: iban = IBAN(iban).formatted except ValueError: return withdrawal(request, error_message='Nesprávny IBAN', active='eur') try: with transaction.atomic(): balance = Balance.objects.filter(user=request.user) balance.update(eur=F('eur') - sum_eur) Withdrawal_eur.objects.create( user=request.user, time_created=timezone.now(), eur=sum_eur, is_pending=True, iban=iban, ) if balance[0].eur < 0: raise ValueError except ValueError: return withdrawal(request, error_message='Nesprávna hodnota', active='eur') return withdrawal(request, ok_message='Požiadavka zaregistrovaná', active='eur')
def onGen(): def onCopy(): clip = tk.Tk() clip.withdraw() clip.clipboard_clear() clip.clipboard_append(iban_get) clip.destroy() m_box.showinfo('Success', 'iBAN Copied Successfully') get_country = country_code.get() get_bank = bank_code.get() get_account = account_code.get() if get_country != '' and get_account != '' and get_bank != '': iban_get = IBAN.generate(get_country, bank_code=get_bank, account_code=get_account) got_iBan = ttk.Label(root, text=f"Your iBAN is {iban_get}", font="arial 12 bold") got_iBan.grid(row=1, column=0, padx=50, pady=2) btncopy = ttk.Button(root, text="Copy iBAN", command=onCopy) btncopy.grid(row=2, columnspan=3, padx=50, pady=2, ipady=5) m_box.showinfo('Success', 'iBAN Generated Successfully') else: m_box.showerror('Error', 'Please Fill Every Boxes Carefully !')
def validate_iban(value): try: IBAN(value) except ValueError: raise ValidationError( _('%(value)s is not a valid IBAN'), params={'value': value}, )
def __init__(self, ctx, label, start, end): super(IBANResult, self).__init__(ctx, label, start, end) try: iban = IBAN(label) self.key = self.label = iban.compact self.countries = [iban.country_code] except ValueError: self.valid = False
def clean_iban(self): input_iban = self.cleaned_data['iban'] try: iban_obj = IBAN(input_iban) except ValueError: raise forms.ValidationError( _('The IBAN you entered does not seem to be correct!')) return iban_obj.compact
def __is_valid_iban(self, account_nr): try: IBAN(account_nr) print 'VALID IBAN: ' + account_nr return True except ValueError as e: print 'INVALID IBAN: ' + str(e) return False
def iban(self, value: Optional[str]): try: if self._iban is not None: self._iban = IBAN(value) else: self._iban = None except ValueError as e: logger.warning( f"Got invalid IBAN '{value}' (type{type(value)}) - {e}")
def test_iban_properties(): iban = IBAN('DE42430609677000534100') assert iban.bank_code == '43060967' assert iban.branch_code == '' assert iban.account_code == '7000534100' assert iban.country_code == 'DE' assert iban.bic == 'GENODEM1GLS' assert iban.formatted == 'DE42 4306 0967 7000 5341 00' assert iban.length == 22
def test_iban_properties(): iban = IBAN("DE42430609677000534100") assert iban.bank_code == "43060967" assert iban.branch_code == "" assert iban.account_code == "7000534100" assert iban.country_code == "DE" assert iban.bic == "GENODEM1GLS" assert iban.formatted == "DE42 4306 0967 7000 5341 00" assert iban.length == 22
def on_entry_changed(self, entry): if entry is self.entry_name: if not len(entry.get_text()): self.set_entry_status(entry, False, "Please enter an account name.") self.page_1_name = False else: self.set_entry_status(entry, True, None) self.page_1_name = True elif entry is self.entry_owner: if not len(entry.get_text()): self.set_entry_status(entry, False, "Please enter an account owner.") self.page_1_owner = False else: self.set_entry_status(entry, True, None) self.page_1_owner = True elif entry is self.entry_iban: iban = None try: iban = IBAN(entry.get_text()) self.set_entry_status(entry, True, None) self.page_1_iban = True except: self.set_entry_status(entry, False, "Please enter an account owner.") self.page_1_iban = False if iban: threading.Thread(target=self.async_fints_url_finder, args=(iban, ), daemon=True).start() elif entry is self.entry_url: try: url = urlparse(entry.get_text() if entry.get_text() else entry. get_placeholder_text()) self.set_entry_status(entry, True, None) except: self.set_entry_status(entry, False, "Please enter the banks FinTS URL.") elif entry is self.entry_login: if not entry.get_text(): self.set_entry_status(entry, False, "Please enter FinTS login name.") else: self.set_entry_status(entry, True, None) elif entry is self.entry_pass: if not entry.get_text(): self.set_entry_status(entry, False, "Please enter FinTS password.") else: self.set_entry_status(entry, True, None) self.set_page_complete( self.get_nth_page(0), self.page_1_name and self.page_1_owner and self.page_1_iban) self.set_page_complete(self.get_nth_page(1), False) #Fixme
def validate(self, value: IBAN): """Validate the IBAN value. Warning: Some invalid IBANs can pass this validation. Specifically, the SWIFT/BIC number of the bank is not verified to be valid. A crafted IBAN value with a correct checksum but fake BIC slip through. Args: value: The IBAN value to validate. """ errors = super().validate(value) try: value.validate() except ValueError as err: errors.append(f'IBAN INVALID: {err}') return errors
def validate_iban(string): try: iban = IBAN(string) except ValueError: raise ValueError(_('utils.validate-iban.invalid-iban')) if iban.country_code != 'DE': raise ValueError(_('utils.validate-iban.country-code-not-de')) return iban.formatted
def validate(self, iban, **kwargs): iban = stringify(iban) if iban is None: return False try: IBAN(iban) return True except ValueError as ex: print(ex) return False
def generate_data(self): if not self.canary_queued: self.canary_queued = True return self.CANARY account = random.randint(0, 9999999999) bank = random.choice(DUTCH_BICS) key = IBAN.generate(self.country, bank, str(account)) # data = strgen.StringGenerator('[\d\w]{{{size}}}'.format(size=self.data_size)).render() data = DATA return key, data
def generate(request): country_code = request.POST.get('country', 'default') bank_code = request.POST.get('bkcode', 'default') account_code = request.POST.get('accode', 'default') print(country_code) print(bank_code) print(account_code) try: iban = IBAN.generate(country_code, bank_code=bank_code, account_code=account_code) parmas = {'iBAN_Goted':iban,} except ValueError: return render(request, 'error.html') else: return render(request, 'generate.html', parmas)
def generate_iban_for_bank(self, bank_code: str) -> IBAN: """ Generates an iban for given bank code. :param bank_code: bank code :return: IBAN object """ try: return IBAN.generate(self.country_code, bank_code, self.generate_account_part(bank_code)) except ValueError as e: raise Exception( 'We generated an invalid IBAN. ' 'This means, that probably there is a bug in the mechanism generating IBAN or the library we use. Error: {0}' .format(e))
def clean_iban_number(self): """ Default clean method of iban_number to check valid iban using schwifty Python library. schwifty need to pass iban number strinf format. Library returns excpetion if not validated. else return same number. """ try: iban = IBAN(self.cleaned_data.get("iban_number")) if iban: return self.cleaned_data.get("iban_number") except Exception as e: raise forms.ValidationError( 'This Iban is not valid. Please correct and try again.') return self.cleaned_data.get("iban_number")
def errors(self): api_errors = super(BankInformation, self).errors() if api_errors.errors: return api_errors try: IBAN(self.iban) except (ValueError, TypeError): api_errors.add_error('iban', f"L'IBAN renseigné (\"{self.iban}\") est invalide") try: BIC(self.bic) except (ValueError, TypeError): api_errors.add_error('bic', f"Le BIC renseigné (\"{self.bic}\") est invalide") return api_errors
def regenerate_iban(old_iban: str) -> str: """ Regenerates an IBAN number (replaces the account number, while keeping the country and bank part) :param old_iban: old IBAN number :return: new iban as string """ try: iban = IBAN(old_iban) except ValueError as e: logger.warning( 'Old IBAN is invalid, leaving it unmodified. IBAN: {0}, error: {1}' .format(old_iban, e)) return old_iban return __get_country_generator( iban.country_code).regenerate_iban(iban).compact
def check_bank(self): if not self.bank or not self.bank.bic: return if IBAN and BIC: iban = IBAN(self.iban) bic = BIC(self.bank.bic) if (iban.bic and iban.bic != bic and ( iban.country_code != bic.country_code or (iban.bank_code or iban.branch_code) not in bic.domestic_bank_codes)): raise AccountValidationError( gettext('bank.msg_invalid_iban_bic', account=self.rec_name, bic=iban.bic))
def save(self, *args, **kwargs): if self.iban_ou_ccp: try: iban = IBAN(self.iban_ou_ccp) self.iban_ou_ccp = iban.formatted except: pass if self.mobile: try: self.mobile = phonenumbers.format_number(phonenumbers.parse(self.mobile, "CH"), phonenumbers.PhoneNumberFormat.INTERNATIONAL) except: pass super(TruffeUser, self).save(*args, **kwargs)
def _sanatize_data(data: List[str]) -> List[str]: """Remove 'bad stuff' from csv dataset. Parameters ---------- data: List[str] CSV data row. Returns ------- data: List[str]: Ready-to-go CSV data row. """ # name umlauts = { ord('Ä'): 'Ae', ord('ä'): 'ae', ord('Ü'): 'Ue', ord('ü'): 'ue', ord('Ö'): 'Oe', ord('ö'): 'oe', ord('ß'): 'ss' } data[0] = unidecode(data[0].translate(umlauts)) # BIC if data[2] == '': data[2] = str(IBAN(data[1]).bic) # money amount if '€' in data[3]: data[3] = data[3].strip().translate({ord('€'): ''}) data[3] = data[3].translate({ord(x): '' for x in [',', '.']}) # create description data[4] = f'{data[4]} {data[5]} {data[6]}' data.pop(6) data.pop(5) # mandate date data[6] = datetime.strptime( data[6], '%d.%m.%Y').date() if data[6] else date.today() # execution date data[7] = datetime.strptime( data[7], '%d.%m.%Y').date() if data[7] else date.today() return data
def test_parse_iban_allow_invalid(number): iban = IBAN(number, allow_invalid=True) with pytest.raises(ValueError): iban.validate()
def test_generate_iban(components, compact): iban = IBAN.generate(*components) assert iban.compact == compact
def test_generate_iban_invalid(country_code, bank_code, account_code): with pytest.raises(ValueError): IBAN.generate(country_code, bank_code, account_code)