ModelForm和单元测试的Bizzare问题:TypeError:getattr():属性名称必须为字符串

时间:2019-01-31 22:04:53

标签: python django forms

我不知道是什么

models.py

class Sound(models.Model):
    SEX_CHOICES = (
            ('M', 'Male'),
            ('F', 'Female')
    )
    phrase1 = models.CharField(max_length=300)
    phrase2 = models.CharField(max_length=300)
    language = models.CharField(max_length=50)
    num_words = models.PositiveSmallIntegerField(verbose_name="number of words")
    num_syllables = models.PositiveSmallIntegerField(verbose_name="number of syllables")
    sex = models.CharField(max_length=1, choices=SEX_CHOICES)
    voice = models.BooleanField(verbose_name="synthetic voice")
    speaker_name = models.CharField(max_length=50)
    sound_hash = models.CharField(max_length=40, primary_key=True, editable=False)
    key = models.CharField(max_length=200, editable=False, default="", null=True, help_text="Amazon S3 key")

forms.py

from django import forms
class LessonSoundForm(forms.ModelForm):
    class Meta:
        model = Sound
        fields = ["phrase1", "phrase2", "num_words", "num_syllables"]

tests.py

from django.test import TestCase
from forms import LessonSoundForm
class LessonSoundForm(TestCase):
    def setUp(self):
        self.sound_data = {
                "phrase1": "Poop",
                "phrase2": "Knuckle",
                "num_words": 1,
                "num_syllables": 1
        }

    def test_lesson_sound_form_validates_with_good_data(self):
        form = LessonSoundForm(data=self.sound_data)
        self.assertTrue(form.is_valid())

这似乎超级简单,所有其他测试都使用ModelForm进行验证。但是,我收到此错误:

line 20, in test_lesson_sound_form_validates_with_good_data
        form = LessonSoundForm(data=self.sound_data)
    TypeError: __init__() got an unexpected keyword argument 'data'

如果不使用data参数运行它,则会得到:

    form = LessonSoundForm(self.sound_data)
  File "/usr/lib/python3.6/unittest/case.py", line 397, in __init__
    testMethod = getattr(self, methodName)
TypeError: getattr(): attribute name must be string

这似乎是一个非常基本的情况,我不知道可能出了什么问题。我认为这只是一天的结束,我想念一些愚蠢的东西。

1 个答案:

答案 0 :(得分:2)

from forms import LessonSoundForm
                  ^^^^^^^^^^^^^^^
class LessonSoundForm(TestCase):
      ^^^^^^^^^^^^^^^

由于名称相同,在为测试用例定义新类时,您将覆盖LessonSoundForm