5
You can mock the get_or_create()
method, as well as the skill
relation to let your test run without accessing the database.
def test_update_skills(self):
def mock_get_or_create(title):
return title, True
mock_skill = set()
with mock.patch('analytics.models.Skill.objects.get_or_create',
mock_get_or_create), \
mock.patch.object(UserProfile, 'skill', mock_skill):
userprofile = UserProfile()
cleaned_skills = ['mysql', 'unix']
userprofile.update_skills(cleaned_skills)
self.assertEqual({'mysql', 'unix'}, mock_skill)
I’m helping out with the django_mock_queries
project that helps provide a bunch of Django queryset features without accessing the database. It’s made a bunch of our tests way faster.
3
- Your test looks strange
-
You can test model methods without creating records in database, just don’t use .create() or .save():
def test_my_method(self): my_model = MyModel(someattr='someval', ...) self.assertEqual(my_model.my_method(), ...)
-
Sometimes it is good decision to mock .save() method to disable creating records in database and speedup tests. See few examples of how You can use mock in tests: http://nanvel.name/2014/04/testing-django-application#patchmock
- [Django]-How to query for distinct groups of entities which are joined via a self-referential many-to-many table?
- [Django]-Django URL Config – Match filename
- [Django]-Django on Strato webspace
1
Try to use Mixer:
from mixer.backend.django import mixer
skill = mixer.blend(Skill, category__title='foo')
userprofile = mixer.blend(UserProfile, user__username='john')
- [Django]-What do I add to my requirements.txt in Django directory in order to push it to Heroku?
- [Django]-Get highest count and corresponding value in Django query
- [Django]-Django-Userena: adding extra non-null fields to a user's profile
- [Django]-CodeIgniter authentication, permissions and admin system, or any other PHP equivilant of Django?
Source:stackexchange.com