#! /usr/bin/env python
import ktoblzcheck
import unittest


class TestAccountNumberCheck(unittest.TestCase):

    def setUp(self):
        self.anc = ktoblzcheck.AccountNumberCheck()

    def test_bankCount(self):
        self.assertTrue(self.anc.bankCount > 0)

    def test_findBank_success(self):
        res = self.anc.findBank(str('20010020').encode('ascii'))
        self.assertIsInstance(res, ktoblzcheck.Record)
        if isinstance(res, ktoblzcheck.Record):
            self.assertEqual(res.bankId, 20010020)
            self.assertEqual(res.bankName.decode('ascii'), 'Postbank Ndl der DB Privat- und Firmenkundenbank')
            self.assertEqual(res.location.rstrip().decode('ascii'), 'Hamburg')

    def test_findBank_fail(self):
        self.assertFalse(self.anc.findBank(b'20010033'))


class TestIban(unittest.TestCase):

    def setUp(self):
        s1 = " iban fr14 2004 1010 0505 0001 3m02 606"
        self.iban1 = ktoblzcheck.Iban(s1.encode('ascii'))

        s2 = "IBAN DE66 2007 0024 0929 1394 00"
        self.iban2 = ktoblzcheck.Iban(s2.encode('ascii'))

    def test_transmissionForm(self):
        tf = self.iban1.transmissionForm()
        self.assertEqual(tf.decode('ascii'), 'FR1420041010050500013M02606')

        tf = self.iban2.transmissionForm()
        self.assertEqual(tf.decode('ascii'), 'DE66200700240929139400')


class TestIbanCheck(unittest.TestCase):

    def setUp(self):
        self.ic = ktoblzcheck.IbanCheck()
        self.s = " iban fr14 2004 1010 0505 0001 3m02 606"

    def test_selftest(self):
        self.assertTrue(ktoblzcheck.kto.IbanCheck_selftest(self.ic))

    def test_check(self):
        iban1 = ktoblzcheck.Iban(self.s.encode('ascii'))
        res = self.ic.check(iban1)
        self.assertEqual(res, 0)

        iban2 = ktoblzcheck.Iban(str('FR1420041010050500013X02606').encode('ascii'))
        res = self.ic.check(iban2)
        self.assertEqual(res, 6)

    def test_resultText(self):
        rt = ktoblzcheck.IbanCheck.resultText(0)
        self.assertEqual(rt.decode('ascii'), 'IBAN is ok')
        rt = ktoblzcheck.IbanCheck.resultText(6)
        self.assertEqual(rt.decode('ascii'), 'IBAN has incorrect checksum')

    def test_bic_position(self):
        iban = ktoblzcheck.Iban(str("IBAN DE66 2007 0024 0929 1394 00").encode('ascii'))
        iban_tf = iban.transmissionForm()
        start, end = self.ic.bic_position(iban)
        self.assertEqual(start, 4)
        self.assertEqual(end, 12)
        self.assertEqual(iban_tf.decode('ascii')[start:end], '20070024')


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