def test_handle_image(self):
     self.handler = InputHandler(db="test")
     header = {'Authorization':"michau:pass2"}
     with open("wizytowka/1.jpg", "rb") as file:
         self.handler.handle_image(file.read(), header)
         db = DataBase()
         print(db.view_database("michau"))
Beispiel #2
0
class InputHandler:
    cookies = {}

    def __init__(self, db="user"):
        self.DE = DataExtractor()
        self.db = DataBase()
        self.handlers = {
            #  "/register": lambda data, headers: self.add_user(data),
            # "/download": lambda headers: self.send_databse(headers),
            "/add_user":
            lambda data, headers: self.add_user(data),
            "/remove_user":
            lambda data, headers: self.remove_user(data, headers),
            "/login":
            lambda headers: self.login(headers),
            "/get_data":
            lambda headers: self.get_data(
                headers),  #todo maybe separate get and post callbacks
            "/handle_image":
            lambda data, headers: self.handle_image(data, headers),
            "/change_password":
            lambda data, headers: self.change_password(data, headers),
            "/change_data":
            lambda data, headers: self.change_data(data, headers),
            "/remove_record":
            lambda data, headers: self.remove_record(data, headers),
        }

    def add_user(self, inp):
        data = self.decode_json(inp)
        print(data)
        return 200 if self.db.add_user(data['name'], data['password'],
                                       data["email"]) else 234

    def change_password(self, data, headers):
        if not self.verify_user(headers):
            return 234
        data = self.decode_json(data)
        name = self.parse_header(headers)[0]
        return 200 if self.db.update_user(name, data['password']) else 234

    def remove_user(self, data, headers):
        data = self.decode_json(data)
        print(data)
        if not self.verify_user(headers):
            return 234
        self.db.remove_user(data['name'])
        return 200

    def login(self, headers):
        if self.verify_user(headers):
            name = self.parse_header(headers)[0]
            InputHandler.cookies[name] = ''.join(
                random.choice(string.digits + string.ascii_letters)
                for _ in range(20))  #todo remove cookies
            return InputHandler.cookies[name]
        else:
            return None

    def get_data(
            self,  #GET
            headers):
        if not self.verify_user(headers):
            return 234
        name = self.parse_header(headers)[0]
        return self.db.view_database(name)

    def remove_record(self, data, headers):
        if not self.verify_user(headers):
            return 234
        record = data.decode('utf-8')
        name = self.parse_header(headers)[0]
        self.db.remove_record(name, record)
        return 200

    def change_data(self, data, headers):
        if not self.verify_user(headers):
            return 234
        data = self.decode_json(data)
        name = self.parse_header(headers)[0]
        return 200 if self.db.update_record(name, data) else 234

    def add_image(self, headers):
        if not self.verify_user(headers):
            return 234
        name = self.parse_header(headers)[0]
        return self.db.view_database(name)

    def verify_user(self, headers):
        name, password = self.parse_header(headers)
        print(name, password)
        if InputHandler.cookies.get(name) == password:
            return True
        return True if self.db.verify_user(name, password) else False

    def handle_image(self, data, headers):
        if not self.verify_user(headers):
            return 234
        user = self.parse_header(headers)[0]

        OCR = self.DE.extract(data)
        self.db.add_record(user, OCR)
        return 200

    def decode_json(self, data):
        ret = data.decode('utf-8')
        return ast.literal_eval(ret)

    def get_handlers(self):
        return self.handlers

    def parse_header(self, header):
        authorization = header.get("Authorization")
        creds = authorization.split(':')
        password = creds[1]
        name = creds[0]
        return name, password

    #todo remove prints


#{
#    "name":"michau",
#    "email":"*****@*****.**",
#    "password":"******"
#}
Beispiel #3
0
class sqlite_test:

    def __init__(self):
        self.db = DataBase()

    def connect(self):
        self.connection = sqlite3.connect(DB_FILENAME)

    def do_stuff(self):
        self.connection.execute("""
        CREATE TABLE IF NOT EXISTS user (
            username TEXT,
            password TEXT,
            email    TEXT,
            data     JSON
        )
        """)
        self.connection.commit()

        some_data = {"sample": "raz",
                     "cos": "cosjescze"}
        jobject = json.dumps(some_data)

        self.connection.executemany("""
        INSERT INTO user (username, password, email, data)
        VALUES (?, ?, ?, ?)
        """, (('wonsz_rzeczny', 'jest_niebezpieczny', "*****@*****.**", jobject),
              ('Radovid', '20pointsShani', "*****@*****.**", jobject)))
        self.connection.commit()

        for row in self.connection.execute("SELECT * FROM user"):
            print(row)

    def test(self):
        self.test_add_user()
        self.test_remove_user()
        self.test_ver()
        self.test_remove_record()
        self.test_add_record()
        self.test_update_record()


    #   name = "Radovid"
     #   data = {"smth":"2",
     #           "moar":"yas"}
     #   db.add_record(name, data)
      #  res = db.view_database("Bob Girlyman")
       # print(res.fetchone())

    def test_ver(self):
        name = "Indrick Boreale"
        password = "******"
        self.db.add_user(name, password)
        res = self.db.verify_user("Indrick Boreale", "SpessMehrens")
        if res is True:
            print("!!! 1ver test passed")
        else:
            print("!!! 1ver test failed")

        self.db.remove_user("Indrick Boreale")
        res = self.db.verify_user("Indrick Boreale", "SpessMehrens")
        if res is False:
            print("!!! 2ver test passed")
        else:
            print("!!! 2ver test failed")

    def test_add_user(self):
        self.db.remove_user("Indrick Boreale")
        name = "Indrick Boreale"
        password = "******"
        self.db.add_user(name, password)
        res = self.db.verify_user("Indrick Boreale", "SpessMehrens")
        print("res val is " + str(res))
        if res is True:
            print("!!!add  user test passed")
        else:
            print("!!!add  user test failed")

    def test_update(self):
        self.db.update_user("test", "silver")

    def test_remove_user(self):
        self.db.remove_user("Indrick Boreale")
        self.db.remove_user("Indrick Boreale")
        res = self.db.verify_user("Indrick Boreale", "SpessMehrens")
        if res is False:
            print("!!!remove test passed")
        else:
            print("!!!remove test failes=d")

    def test_add_record(self):
        name = "Bob Gyrlyman"
        dataname = "Marneus"
        rec = {dataname: {"password": "******", "email": "*****@*****.**"}}
        js = json.dumps(rec)
        self.db.add_record(data=js, name=name)
        self.db.add_record(data=js, name=name)
        db = self.db.view_database(name)
        if db[dataname] == rec[dataname]:
            print("!!!1 add record test passed")
        else:
            print("!!!1 add record test failed")

        self.db.remove_record(name, dataname)
        self.db.add_record(data=js, name=name)
        db = self.db.view_database(name)
        if db[dataname] == rec[dataname]:
            print("!!!2 add record test passed")
        else:
            print("!!!2 add record test failed")

    def test_update_record(self):
        name = "Bob Gyrlyman"
        dataname = "Marneus"
        rec = {dataname: {"password": "******", "email": "*****@*****.**"}}
        js = json.dumps(rec)
        self.db.add_record(data=js, name=name)
        up = {dataname: {"password": "******", "email": "*****@*****.**"}}
        self.db.update_record(name, up)
        res = self.db.view_database(name)
        if res[dataname] == up[dataname]:
            print("!!! update record test passed")
        else:
            print("!!! update record test failed")

    def test_remove_record(self):
        name = "Bob Gyrlyman"
        dataname = "Marneus"
        rec = {dataname: {"password": "******", "email": "*****@*****.**"}}
        js = json.dumps(rec)
        self.db.add_record(data=js, name=name)
        print("remove")
        self.db.remove_record(name, dataname)
        self.db.remove_record(name, dataname)
        db = self.db.view_database("Bob Gyrlyman")
        try:
            db[dataname]
        except KeyError:
            print("!!! remove record test pass")
            return
        print("!!! remove record test failed")
Beispiel #4
0
class DatabaseTest(unittest.TestCase):
    def setUp(self):
        try:
            os.remove("Database/Data/database.db")
        except FileNotFoundError:
            print("file already removed!")
        self.db = DataBase()
        self.user1 = {
            "name": "Rick Sanchez",
            "password": "******",
            "email": "*****@*****.**"
        }
        self.user2 = {
            "name": "Talos Valcoran",
            "password": "******",
            "email": "*****@*****.**"
        }
        self.user3 = {
            "name": "Uzas",
            "password": "******",
            "email": "*****@*****.**"
        }

        self.add_user = lambda user: self.db.add_user(user["name"], user[
            "password"], user["email"])

        self.recname1 = "Indrick Boreale"
        self.recname2 = "Vandred Anrathi"
        self.recname3 = "Cyrion"
        self.rec1 = {
            self.recname1: {
                "email": "*****@*****.**",
                "telefon": "13432425253",
                "website": "www.cptBoreale.dr"
            }
        }
        self.rec2 = {
            self.recname2: {
                "alias": "The Exalted",
                "email": "*****@*****.**",
                "adres": "The Covenant"
            }
        }
        self.rec3 = {
            self.recname3: {
                "fax": "123221",
                "affiliation": "slaanesh",
                "email": "*****@*****.**"
            }
        }

    def test_verify(self):
        self.add_user(self.user1)
        self.assertEqual(
            True,
            self.db.verify_user(self.user1["name"], self.user1["password"]),
            "1 Verify true test failed!")
        self.add_user(self.user1)
        self.assertEqual(
            False,
            self.db.verify_user(self.user1["name"], self.user2["password"]),
            "2 Verify false test failed!")
        self.add_user(user=self.user1)
        self.assertEqual(
            False,
            self.db.verify_user(self.user2["name"], self.user1["password"]),
            "3 Verify false test failed!")

    def test_add_user(self):
        self.db.remove_user(self.user1["name"])
        self.add_user(self.user2)
        self.assertEqual(
            True,
            self.db.verify_user(self.user2["name"], self.user2["password"]),
            "1 Add to empty db test failed!")
        self.add_user(self.user1)
        self.db.add_user(self.user2["name"], self.user1["password"],
                         self.user1["email"])
        self.db.add_user(self.user1["name"], self.user1["password"],
                         self.user1["email"])
        self.assertEqual(
            True,
            self.db.verify_user(self.user1["name"], self.user1["password"]),
            "2 Add to non empty db test failed!")
        self.assertEqual(
            True,
            self.db.verify_user(self.user2["name"], self.user2["password"]),
            "3 Add override db test failed!")
        self.db.remove_user(self.user2["name"])
        ret = self.add_user(self.user2)
        self.assertEqual(True, ret, "4 Add incorect return value!")
        ret = self.add_user(self.user2)
        self.assertEqual(False, ret, "5 Add incorect return value!")

    def test_remove_user(self):
        self.db.remove_user(self.user1["name"])
        self.db.remove_user(self.user2["name"])
        self.assertEqual(
            False,
            self.db.verify_user(self.user1["name"], self.user1["password"]),
            "1 Remove not existing record test failed!")
        self.add_user(self.user2)
        self.db.remove_user(self.user2["name"])
        self.assertEqual(
            False,
            self.db.verify_user(self.user1["name"], self.user1["password"]),
            "2 Remove only record test failed!")
        self.add_user(self.user1)
        self.add_user(self.user2)
        self.db.remove_user(self.user1["name"])
        self.assertEqual(
            False,
            self.db.verify_user(self.user1["name"], self.user1["password"]),
            "3.1 Remove one record test failed! - record not removed")
        self.assertEqual(
            True,
            self.db.verify_user(self.user2["name"], self.user2["password"]),
            "3.2 Remove one record test failed! - other record corrupted!")
        self.db.remove_user(self.user1["name"])
        self.db.remove_user(self.user1["name"])
        self.db.remove_user(self.user1["name"])
        self.assertEqual(
            False,
            self.db.verify_user(self.user1["name"], self.user1["password"]),
            "4.1 Remove not existing record test failed! - record not removed")
        self.assertEqual(
            True,
            self.db.verify_user(self.user2["name"], self.user2["password"]),
            "4.2 Remove not existing record test failed! - other record corrupted!"
        )

    def test_update_user(self):
        # assusre that user1 is self.user1
        self.db.remove_user(self.user1["name"])
        self.add_user(self.user1)

        new_pass = "******"
        self.db.update_user(self.user1["name"], new_pass)

        self.assertEqual(
            False,
            self.db.verify_user(self.user1["name"], self.user1["password"]),
            "1 Update user updated failed! - record not changed")
        self.assertEqual(True, self.db.verify_user(self.user1["name"],
                                                   new_pass),
                         "2 Updated user test failed!")

    def test_add_record(self):
        # assusre that user1 is self.user1
        self.db.remove_user(self.user1["name"])
        self.add_user(self.user1)

        self.db.add_record(self.user1["name"], self.rec1)
        res = self.db.view_database(self.user1["name"])
        self.assertEqual(res, self.rec1,
                         "1 Add record Failed - first record, first user ")

        self.db.remove_user(self.user2["name"])
        self.add_user(self.user2)

        self.db.add_record(self.user2["name"], self.rec1)
        res = self.db.view_database(self.user2["name"])
        self.assertEqual(res, self.rec1,
                         "2 Add record Failed - first record, second user ")

        self.db.add_record(self.user1["name"], self.rec2)
        res = self.db.view_database(self.user1["name"])
        rec = copy.deepcopy(self.rec1)
        rec.update(self.rec2)
        self.assertEqual(res, rec,
                         "3 Add record Failed - second record, first user ")

        self.db.add_record(self.user1["name"], self.rec3)
        res = self.db.view_database(self.user1["name"])
        rec.update(self.rec3)
        self.assertEqual(res, rec,
                         "4 Add record Failed - third record, first user ")

        # TODO duplicate names

    def test_remove_record(self):
        self.db.remove_user(self.user1["name"])
        self.db.remove_user(self.user2["name"])
        self.add_user(self.user1)

        self.db.add_record(self.user1["name"], self.rec1)
        self.db.remove_record(self.user1["name"], self.recname1)
        self.assertEqual({}, self.db.view_database(self.user1["name"]),
                         "1 Remove record - only one record ")

        self.db.add_record(self.user1["name"], self.rec1)
        self.db.add_record(self.user1["name"], self.rec2)
        self.db.remove_record()

    def test_thread_safety(self):
        thread = Thread(target=self.async_fun)
        thread2 = Thread(target=self.async_fun)
        thread3 = Thread(target=self.async_fun)
        thread.start()
        thread2.start()
        thread3.start()

        thread.join()
        thread2.join()
        thread3.join()
        self.remove_user("Wonsz")
        self.add_user(self.new_user)
        self.assertEqual(True, self.verify_user("Wonsz", "rzeczny"),
                         "Thread test failed!")

    def async_fun(self):
        i = 0
        while i < 15:
            i += 1
            self.add_user(user=self.new_user)
            self.update_user(user=self.updated)
            self.remove_user("Wonsz")
            self.add_user(user=self.new_user2)
            self.verify_user("Wonsz", "rzeczny")
            self.remove_user("Wonsz2")

    def run_all(self):
        self.setUp()
        self.test_verify()
        self.test_add_user()
        self.test_remove_user()
        self.test_update_user()
        self.test_add_record()
        self.test_remove_record()