Python装饰器; TypeError:“ NoneType”对象不可调用

时间:2020-11-07 21:20:43

标签: python

我创建了一个装饰器,该装饰器构成了与Sqlite数据库的连接。尝试测试正在装饰的功能Event.create()时,出现以下错误: TypeError:'NoneType'对象不可调用。不知道是什么原因导致此错误。如果与 @classmethod 装饰器有关,我不确定为什么会这样?我在装饰员方面没有太多经验,所以我想了解为什么?

main.py


import sqlite3

db = sqlite3.connect("main_db.db")

def db_connect(func):
    global db
    def wrapper_db_connect(*args, **kwargs):
        try:
            with db:
                return func()
        except sqlite3.IntegrityError:
            pass
        finally:
            db.close()



class Event:

    @db_connect
    @classmethod
    def create(cls, *args, **kwargs):
        db.execute("""
            INSERT INTO event VALUES(:name, :occurs: :desc)
        """, kwargs)

    @db_connect
    @classmethod
    def delete(cls, *args, **kwargs):
        pass

tests.py


import unittest
import sqlite3

from main import Event


class TableSetup(unittest.TestCase):
    def setUp(self):
        self.db = sqlite3.connect(":memory:")
        with self.db:
            self.db.execute("""
                CREATE TABLE event (
                    name TEXT UNIQUE,
                    occurs TEXT,
                    description TEXT
                )
                """)

    def tearDown(self):
        print("DROP")
        with self.db:
            self.db.execute("DROP TABLE event")


class TestEventOrganizer(TableSetup):

    def setUp(self):
        super().setUp()
        self.event_user_data = {
            'name': 'Event A',
            'occurs': '2020-3-1',
            'desc': 'Event A'
        }

    def test_create_event(self):

        Event.create(**self.event_user_data)

        self.assertEqual(db.total_changes, 1)
        self.assertEqual(str(self.stored_event), "Event A")

    def tearDown(self):
        super().tearDown()

0 个答案:

没有答案