python在测试中询问现有参数

问题描述:

我尝试测试信号。我在app.signals.pypython在测试中询问现有参数

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, 
     ) 

func被创建任务后称为task.models

@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' 

你可以从错误中看到,你是不是通过内部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)