def test_save_tags_commit_false_not_call_save_tags( self, _save_tags_mock: mock.MagicMock): """Should not call _save_tags when commit=False.""" obj_dict = self.get_tutorial_dict() form = TutorialForm(obj_dict, instance=self.object) form.save(commit=False) self.assertFalse(_save_tags_mock.called)
def test_clean_tags_invalid_data(self): """Should not validate when a TutorialTag object is invalid.""" tag_title_max_length = TutorialTag._meta.get_field("title").max_length invalid_tag = "a" * (tag_title_max_length + 1) obj_dict = self.get_tutorial_dict(new_tags=invalid_tag) form = TutorialForm(obj_dict) self.assertFalse(form.is_valid())
def test_save_tags_commit_true_call_save_tags( self, _save_tags_mock: mock.MagicMock): """Should call _save_tags when commit=True.""" obj_dict = self.get_tutorial_dict( tutorial=baker.prepare_recipe("learning.tutorial")) form = TutorialForm(obj_dict) form.save(commit=True) self.assertTrue(_save_tags_mock.called)
def test_save_tags_commit_false_assign_save_tags( self, _save_tags_mock: mock.MagicMock): """Should assign save_tags to _save_tags when commit=False.""" obj_dict = self.get_tutorial_dict( tutorial=baker.prepare_recipe("learning.tutorial")) form = TutorialForm(obj_dict) form.save(commit=False) self.assertEqual(form.save_tags, form._save_tags)
def test_clean_tags_valid_data(self): """Should split tags by `,` and turn each of them into a TutorialTag object when all tags are valid. """ new_tags = self.generate_tags() obj_dict = self.get_tutorial_dict(new_tags=new_tags) form = TutorialForm(obj_dict) form.is_valid() self.assertTagsEquals(form.cleaned_data["tags"], new_tags)
def form_valid(self, form: TutorialForm): tutorial: Tutorial = form.save(commit=False) # Set tutorial author tutorial.author = self.request.user # Save tutorial tutorial.save() # Save many-to-many relations (categories here) form.save_m2m() # Save tutorial tags form.save_tags() messages.success( self.request, f'آموزش "{tutorial.title}" با موفقیت افزوده شد' ) return redirect(self.get_success_url())
def test_tags_initial_value(self): """Should connect tutorial's tag names by `,` as tags' initial value. """ form = TutorialForm(instance=self.object) self.assertEqual( form.fields["tags"].initial, ",".join([str(tag) for tag in self.tags]), )
def test_save_tags_unchanged_tag_call_tutorial_on_edit(self): """_save_tags() should call tutorial's on_edit when tags has changed. """ with mock.patch.object(self.object, "on_edit") as on_edit_mock: obj_dict = self.get_tutorial_dict() form = TutorialForm(obj_dict, instance=self.object) form.is_valid() form._save_tags() self.assertFalse(on_edit_mock.called)
def test_save_tags_create_in_db(self): """_save_tags() should save all of the new tags for given tutorial. """ new_tags = self.generate_tags() obj_dict = self.get_tutorial_dict(new_tags=new_tags) form = TutorialForm(obj_dict, instance=self.object) form.is_valid() form._save_tags() self.assertTagsEquals(new_tags, self.object.tags.all())