def test_content_returns_the_raw_value_when_converted_to_a_string(self): # Setup test = DummyModel() test.content = '**hello world!**' test.save() # Run & check assert force_text(test.content) == '**hello world!**'
def test_correctly_saves_its_data(self): # Run & check for markup_text, expected_html_text in self.MARKUP_TEXT_FIELD_TESTS: test = DummyModel() test.content = markup_text test.save() assert test.content.rendered.rstrip() == expected_html_text
def test_parameters_in_qs(self): DummyModel(name="qux").save() DummyModel(name="mux").save() self._run(name="qux") self.assertFalse(DummyModel.objects.filter(name="qux").exists()) self.assertTrue(DummyModel.objects.filter(name="mux").exists())
def test_should_not_accept_images_with_incorrect_sizes_or_dimensions(self): # Setup test = DummyModel() field = test._meta.get_field('validated_image') invalid_images = ['too_large_image', 'too_wide_image', 'too_high_image', ] # Run & check for img in invalid_images: field.save_form_data(test, self.images_dict[img]) with pytest.raises(ValidationError): test.full_clean()
def test_can_accept_none_values(self): # Setup test = DummyModel() test.content = None # Run test.save() # Check assert test.content is None rendered = hasattr(test.content, 'rendered') assert not rendered
def test_can_resize_images_before_saving_them(self): # Setup test = DummyModel() # Run field = test._meta.get_field('resized_image') field.save_form_data(test, self.images_dict['to_be_resized_image']) test.full_clean() test.save() # Check image = Image.open(BytesIO(test.resized_image.read())) assert image.size == (RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT)
def test_default_return_value_for_subtask(self): d1 = DummyModel(name="qux") d1.save() d2 = DummyModel(name="mux") d2.save() self._run(persist_results=True) self.assertEqual(DummyModel.objects.filter(name=str([d1.id, d2.id])).count(), 1)
def test_queryset_refreshes_on_each_sprinkling(self): DummyModel(name="foo").save() self._run() # Make sure we don't incorrectly pass this test through sheer luck by generating the number # of models that happens to match the results cache of the SampleSprinkler queryset. # This was a bigger issue in an earlier version of sprinklers, but it still makes me feel good # knowing that this tests pass and sprinklers will always refresh their querset when they run. cur_len = len(SampleSprinkler().get_queryset()) for i in xrange(cur_len + 5): DummyModel(name="foo").save() self._run() for d in DummyModel.objects.all(): self.assertEqual(d.name, "Sprinkled!")
def test_serialized_data(self): instance = DummyModel(pk=12, related=DummyRelated(pk=42).cache()) serializer = DummySerializer(instance) assert serializer.data == { "id": 12, "related": { "type": "related_records", "id": "42" } }
def test_manually_include_excluded_by_default_fields(self): instance = DummyModel(pk=12, related=DummyRelated(pk=42).cache()) serializer = DummyWithExcludeSerializer( instance, context={"include_fields": ["related"]}) self.assertEqual(serializer.data, { "id": 12, "related": { "type": "related_records", "id": "42" } })
def test_show_default_exclude_if_contexts_says_so(self): instance = DummyModel(pk=12, related=DummyRelated(pk=42).cache()) request = mock.Mock(query_params={ "fields[DummyModel]": "related", }) serializer = DummyWithExcludeSerializer(instance, context={"request": request}) self.assertEqual(serializer.data, {"related": { "type": "related_records", "id": "42" }})
def test_show_default_excludes_if_in_data(self): instance = DummyModel(pk=12, related=DummyRelated(pk=42).cache()) serializer = DummyWithExcludeSerializer( instance, data={"related": instance.related}) serializer.is_valid() self.assertEqual(serializer.data, { "id": 12, "related": { "type": "related_records", "id": "42" } })
def test_prefetch_jsonapi(): _get_many = DummyRelated.get_many DummyRelated.get_many = mock.Mock() DummyRelated.get_many.return_value = { 12: DummyRelated(pk=12), 137: DummyRelated(pk=137), 42: DummyRelated(pk=42), } extra_related = mock.Mock(related_id=42, ) dummy_model_1 = DummyModel(pk=12, related_id=137, other_id=12) dummy_model_1.extra_related = extra_related dummy_model_2 = DummyModel(pk=13, related_id=42, other_id=None) dummy_model_2.extra_related = None instances = [ dummy_model_1, dummy_model_2, ] prefetch_jsonapi( instances, { "other": DummyRelated, "related": DummyRelated, "extra_related__related": DummyRelated }, ) assert instances[0]._cache_other == DummyRelated(pk=12) assert instances[0]._cache_related == DummyRelated(pk=137) assert instances[0].extra_related._cache_related == DummyRelated(pk=42) assert instances[1]._cache_other is None assert instances[1]._cache_related == DummyRelated(pk=42) DummyRelated.get_many.assert_called_once() DummyRelated.get_many = _get_many
def test_is_valid_for_failures(self): instance = DummyModel(pk=12, related=DummyRelated(pk=42).cache()) serializer = DummySerializer(instance) for thrown, raised in [ (KeyError, KeyError), (JSONAPIClientError(response=mock.Mock(status_code=500)), JSONAPIClientError), (JSONAPIClientError(response=mock.Mock(status_code=404)), ValidationError), ]: with self.subTest(thrown=thrown, raised=raised): with mock.patch.object(BaseSerializer, "is_valid", side_effect=thrown): self.assertRaises(raised, serializer.is_valid)
def test_provides_access_to_the_raw_text_and_to_the_rendered_text(self): # Setup test = DummyModel() test.content = '**hello**' test.save() field = test._meta.get_field('content') markup_content = '**hello world!**' markup_content_len = len(markup_content) # Run test.content.raw = markup_content markup_bk = test.content test.content = markup_bk test.save() # Check assert field.value_to_string(test) == markup_content assert test.content.rendered.rstrip() == '<p><strong>hello world!</strong></p>' assert len(test.content) == markup_content_len with pytest.raises(AttributeError): print(DummyModel.content.rendered)
def finished(self, results): # Persist results to an external source (the database) so I can unit test this. # Note that it writes the entire result obj as the name if self.kwargs.get('persist_results'): DummyModel(name="%s" % results).save()
def test_init_with_related_none(self): record = DummyModel(related=DummyRelated(pk=42)) self.assertEqual(record.related_id, 42) self.assertEqual(record.related, DummyRelated(pk=42))
def test_assign_to_value_without_pk(self): record = DummyModel() expected = "Cannot assign DummyRelated without pk to DummyModel.related" with self.assertRaisesMessage(ValueError, expected): record.related = DummyRelated()
def test_assign_to_bad_type_value(self): record = DummyModel() expected = "Cannot assign 42: " "DummyModel.related must be a DummyRelated instance" with self.assertRaisesMessage(ValueError, expected): record.related = 42
def test_related_id_is_none(self): record = DummyModel() self.assertIsNone(record.related_id) self.assertIsNone(record.related)
def test_sharded_sprinkler(self): for i in range(10): DummyModel(name="sharded").save() self._run_sharded(name="sharded") self.assertEqual(DummyModel.objects.filter(name="sharded").count(), 0)
def test_is_valid_for_success(self): instance = DummyModel(pk=12, related=DummyRelated(pk=42).cache()) serializer = DummySerializer(instance) with mock.patch.object(BaseSerializer, "is_valid") as patcher: self.assertEqual(serializer.is_valid(), patcher.return_value)
def test_works_with_values_queryset(self): DummyModel(name="foo").save() DummyModel(name="foo").save() self._run(values=True) for d in DummyModel.objects.all(): self.assertEqual(d.name, "Sprinkled!")
def test_objects_get_sprinkled(self): DummyModel(name="foo").save() DummyModel(name="foo").save() self._run() for d in DummyModel.objects.all(): self.assertEqual(d.name, "Sprinkled!")
def test_sprinkler_finished(self): DummyModel(name="qux").save() DummyModel(name="mux").save() self._run(persist_results=True, special_return=True) self.assertEqual(DummyModel.objects.filter(name=str([True, True])).count(), 1)
def test_error_on_subtask_calls_on_error(self): DummyModel(name="fail").save() DummyModel(name="succeed").save() self._run(raise_error=True, persist_results=True, special_return=True) self.assertEqual(DummyModel.objects.filter(name=str([False, True])).count(), 1)
def test_validation_exception(self): DummyModel(name="foo").save() self._run(fail=True, persist_results=True) self.assertTrue(DummyModel.objects.filter(name="foo").exists()) self.assertEqual(DummyModel.objects.filter(name=str(['v_fail'])).count(), 1)
def test_hide_default_excludes(self): instance = DummyModel(pk=12, related=DummyRelated(pk=42).cache()) serializer = DummyWithExcludeSerializer(instance) self.assertEqual(serializer.data, {"id": 12})