python - how to write unittest in Django for method with ListField variable? -
i have never written unit test before. i'm trying write unit test class:
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()}
but i'm not sure how write unit test facebook_friend since it's in list field class:
class listfield(models.textfield): __metaclass__ = models.subfieldbase description = "stores 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 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)
i tried it's not working , i'm not sure how write it:
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)
can me/show me how write unit test one?
i'm going presume instead of testing facebook_friends
want test login method. i'm presuming because example test code telling me.
okay, behaviour want login method
if user given userid exists retrieved database. facebook_friends pass function saved onto friends attribute , return dictionary friends statuses.
if user not exist, create it, set couple of attributes, save , following rest of same code path above. so, unit test user exists code path of login method might this
import unittest mock import patch class userlogintest(unittest.testcase): @patch('model.user.get_friend_statuses') def test_login_when_user_exists(self, mock_get_friend_statuses): # objects.create creates , saves db entry in 1 step user.objects.create(facebook_id='an_id') return_value = user.login('an_id', ['some', 'list', 'items']) user = user.objects.get(facebook_id='an_id') self.assertequal(user.friends, ['some', 'list', 'items']) self.assertequal( return_value, {'data' mock_get_friend_statuses.return_value} ) self.assertisnone(user.status_time)
Comments
Post a Comment