python在测试中询问现有的参数

时间:2017-09-26 09:10:50

标签: python django signals

我尝试测试信号。我在app.signals.py中有信号项

from django.dispatch import Signal 
task_completed = Signal(providing_args=['balance'])

Func位于user.views中,并根据任务成本

更新余额
from django.contrib.messages import success
from users.models import User
from django.db.models import F
from freelance.signals import task_completed


def update_balance(cls, balance):
    User.objects.select_for_update().filter(user_type=User.CUSTOMER).update(
        balance=F('balance') - balance
    )
    User.objects.select_for_update().filter(user_type=User.EXECUTER).update(
        balance=F('balance') + balance
    )
    if success:
        task_completed.send_robust(
            sender=cls,
            balance=balance,
        )
在任务创建后,在task.models中调用

func

@receiver(post_save, sender=Task)
def task_post_save(sender, instance, **kwargs):
    instance.assignee.update_balance(instance.money)

最后测试我想要做的所有这些事情

class TestCharge(TestCase):
    def test_should_send_signal_when_charge_succeeds(self):
        self.signal_was_called = False
        self.total = None

        def handler(sender, balance, **kwargs):
            self.signal_was_called = True
            self.total = balance

        task_completed.connect(handler)

        update_balance(100)

        self.assertTrue(self.signal_was_called)
        self.assertEqual(self.total, 100)

        task_completed.disconnect(handler)

但它给出了错误,如

TypeError: update_balance() missing 1 required positional argument: 'balance'

1 个答案:

答案 0 :(得分:1)

从错误中可以看出,您没有在 update_balance()中传递必需的参数。 错误在这一行:

update_balance(100)

但根据你的功能定义:

def update_balance(cls, balance):

update_balance 需要两个参数,因此您需要像这样更新代码:

class TestCharge(TestCase):
    def test_should_send_signal_when_charge_succeeds(self):
        self.signal_was_called = False
        self.total = None

        def handler(sender, balance, **kwargs):
            self.signal_was_called = True
            self.total = balance

        task_completed.connect(handler)

        update_balance("First value here",100)

        self.assertTrue(self.signal_was_called)
        self.assertEqual(self.total, 100)

        task_completed.disconnect(handler)