我以前从未写过单元测试。我正在尝试为此类编写单元测试:
class User(models.Model):
facebook_id = models.CharField(max_length=200)
friends = ListField()
status = models.CharField(max_length=200)
status_time = models.DateTimeField('date published')
@staticmethod
def login(cls, userid, facebook_friends):
myuser = None
try:
myuser = User.objects.get(facebook_id=userid)
except User.DoesNotExist:
myuser = User()
myuser.status_time = datetime.datetime.now() - datetime.timedelta(minutes=16)
myuser.facebook_id = userid
myuser.save()
# user exists
myuser.friends = facebook_friends
myuser.save()
return {"data":myuser.get_friend_statuses()}
但我不确定如何为 facebook_friend 编写单元测试,因为它在 List Field 类中:
class ListField(models.TextField):
__metaclass__ = models.SubfieldBase
description = "Stores a python list"
def __init__(self, *args, **kwargs):
super(ListField, self).__init__(*args, **kwargs)
def to_python(self, value):
if not value:
value = []
if isinstance(value, list):
return value
return ast.literal_eval(value)
def get_prep_value(self, value):
if value is None:
return value
return unicode(value)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
我试过这样的东西,但它不工作,我不知道如何写它:
class ListField(models.TextField):
def test_wrong_username(self):
user = User.login(self, 'username1', ['one', 'two', 'three'])
errcode = User.login(self, 'username2', ['one', 'two', 'three'])
self.assertEqual(errcode, user)
谁能帮我/告诉我如何为此编写单元测试?