简体   繁体   English

如何将参数传递给类中的装饰器

[英]how to pass arguments to a decorator in a class

I have a unit test that loads some data in the database to test against.我有一个单元测试,它在数据库中加载一些数据进行测试。 I have created a decorator function for this, to be used on a test case我为此创建了一个装饰器函数,用于测试用例

class TestCompany(unittest.TestCase):
    def setUp(self):
        ...
        self.engine = create_engine(db_url)
        Session = sessionmaker(bind=self.engine)
        self.session = Session() 


    @loadfixtures(['employee.json'])
    def test_checkdb_employee(self):
        c = self.session.query(Employee).count()
        self.assertEqual(c , 20)
    

However, I need to somehow pass self.engine to the decorator.但是,我需要以某种方式将self.engine传递给装饰器。

@loadfixtures(self.engine, ['employee.json']) does not work, because self is not available there. @loadfixtures(self.engine, ['employee.json'])不起作用,因为self在那里不可用。

I created this solution for this, but is there a simpler (more readable) solution?我为此创建了这个解决方案,但是有更简单(更易读)的解决方案吗?

    def test_checkdb_employee(self):
        @loadfixtures(['employee.json'])
        def run(engine):
            c = self.session.query(Employee).count()
            self.assertEqual(c , 20)
        return run(self.engine)

     
#decorator
import pandas as pd
 
def loadfixtures( files):
    def decorator(func):
        def wrapped_func(*args, **kwargs):
            for file in files: 
                df = pd.read_json(Path(datafolder).joinpath(file))
                df.to_sql(file.split(".")[0], con=args[0],index=False, if_exists='append')
            return func(*args, **kwargs)
        return wrapped_func
    return decorator

(The engine is used in con=args[0] ) engine用于con=args[0]

self is actually passed as the first argument to test_checkdb_employee . self实际上作为第一个参数传递给test_checkdb_employee So to access your engine in the decorator to use as argument for the con parameter you could just do args[0].engine with args[0] being self (the TestCompany instance).因此,要在装饰器中访问您的engine以用作con参数的参数,您只需执行args[0].engine其中args[0]selfTestCompany实例)。

def loadfixtures(files):
    def decorator(func):
        def wrapped_func(*args, **kwargs):
            for file in files: 
                df = pd.read_json(Path(datafolder).joinpath(file))
                df.to_sql(file.split(".")[0], con=args[0].engine, index=False, if_exists='append')
            return func(*args, **kwargs)
        return wrapped_func
    return decorator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM