예제 #1
0
 def test_save_data_new_image(self):
     """
     Checks whether saving data of a new image creates a new slug
     and sets a position
     """
     # create a new image
     image = models.Image(
         image=get_image_in_memory_data(),
         position=0,
         content_type=ContentType.objects.get_for_model(TestModel),
         object_id=self.object.id
     )
     # use mocks for methods could be called
     image._get_slug = mock.MagicMock(return_value='foo')
     image._get_position = mock.MagicMock()
     image.image.save_files = mock.MagicMock()
     # call the _save_data method
     image._save_data()
     # check whether the _get_slug and the _get_position methods
     # have been called
     image._get_slug.assert_called_once_with()
     image._get_position.assert_called_once_with()
     # check whether the save_files method of the image field
     # has been called with the slug and the name of the image
     image.image.save_files.assert_called_once_with('foo', 'foo.jpg')
예제 #2
0
 def test_get_queryset(self):
     """
     Checks whether images in the query set are sorted by position
     """
     qs = mock.MagicMock()  # mock object returned by parent's method
     # create order_by method
     qs.order_by = mock.MagicMock(return_value='bar')
     # patch parent class to return the mock
     with mock.patch(
         'django.contrib.contenttypes.admin'
         '.GenericInlineModelAdmin.get_queryset',
         return_value=qs
     ) as get_queryset:
         # call method being tested with the mock ImageAdminInline
         result = admin.ImageAdminInline.get_queryset(
             self.inline_admin,
             'request'
         )
         # check whether the parent's method has been called
         # with the same argument
         get_queryset.assert_called_with('request')
     # check whether the order_by method has been called
     # with the 'position' str as an argument
     qs.order_by.assert_called_with('position')
     # check whether the method returns the result of the 'order_by'
     self.assertEqual(result, 'bar')
 def setUp(self):
     """
     Creates a mock object used instead of real form and
     a mock for the 'object_id' field
     """
     # create a form mock object
     self.form = mock.MagicMock(spec=forms.ImageAdminForm)
     # 'fields' is a dict
     self.form.fields = {}
     # create a field mock object
     field = mock.MagicMock()
     # initially the 'model_class' attribute is None
     field.widget.model_class = None
     # set the field mock to the form mock
     self.form.fields['object_id'] = field
 def test_rename_file(self, rename):
     """
     Checks whether the _rename_file method calls the os.rename
     function with proper arguments
     """
     # a mock function to replace the _create_filename method
     mock_func = mock.MagicMock(return_value='baz_bar.jpg')
     self.image_file._create_filename = mock_func
     # set original path
     self.image_file.path = 'gallery/foo_bar.jpg'
     # patch the create_path helper function to return a new path
     with mock.patch.object(
         utils,
         'create_path', 
         return_value='gallery/baz_bar.jpg'
     ) as create_path:
         # call the _rename_files method with a new file name
         image_data.ImageFile._rename_file(self.image_file, 'baz.jpg')
         # check whether the helper function has been called
         # with the result of the _create_filename method
         create_path.assert_called_with('baz_bar.jpg')
     # check whether the mock _create_filename method has been called
     # with the new file name
     mock_func.assert_called_with('baz.jpg')
     # check whether the os.rename function has been called
     # with the original and the new paths
     rename.assert_called_with(
         'gallery/foo_bar.jpg',
         'gallery/baz_bar.jpg'
     )
예제 #5
0
 def test_render_with_image(self, render_to_string):
     """
     Checks whether the render method returns a result of
     the render_to_string function if the method has been
     called with an image
     """
     # set a template name
     self.widget.template_name = "bar"
     # create an image mock
     image = mock.MagicMock()
     # set an URL of the small preview
     image.small_preview_url = 'url'
     # patch the create_image_url so that it returns known result
     with mock.patch.object(utils, 'create_image_data',
                            return_value='data') as create_data:
         # call the method with the image mock
         result = widgets.ImageInlineWidget.render(self.widget, 'name',
                                                   image)
         # check whether the create_image_data helper function has been
         # called with the image
         create_data.assert_called_with(image)
     # check whether the method returns the result of
     # the render_to_string function
     self.assertEqual(result, "foo")
     # check whether the render_to_string function has been called
     # with proper arguments
     render_to_string.assert_called_with(
         'bar',  # the template name
         {
             'preview_src': 'url',  # the URL of small preview
             # the result of the create_image_data function
             # in JSON format
             'image_data': json.dumps('data')
         })
예제 #6
0
 def test_render_with_mark_safe(self, mark_safe):
     """
     Checks whether the widget is rendered properly
     """
     # create a mock widget object
     widget = mock.MagicMock(spec=widgets.ContentTypeSelect)
     # set the js template
     # it should contain %s for URL pattern subtitution
     widget.js = " %s"
     # patch the get_choices_url_pattern helper function
     # so that it returns known value
     with mock.patch.object(
             utils, 'get_choices_url_pattern',
             return_value='foo') as get_url_pattern, mock.patch.object(
                 Select,  # patch parent's method
                 'render',
                 return_value='bar') as render:
         # call the render method
         result = widgets.ContentTypeSelect.render(widget, 'name', 'value')
         # check whether the helper function has been called
         get_url_pattern.assert_called_with()
         # check whether the parent's method has been called
         # with the same arguments
         render.assert_called_with('name', 'value', None)
     # check whether the mark_safe function has been called with rendered
     # template containing a result of the parent's method + the js
     # pattern where %s is replaced with the URL pattern
     # i.e. 'bar' + ' %s' % 'foo'
     mark_safe.assert_called_with('bar foo')
     # check whether the render method returns a result of the mark_safe
     self.assertEqual(result, "baz")
예제 #7
0
 def setUpClass(cls):
     """
     Creates two objects of the TestModel in the database
     """
     cls.widget = mock.MagicMock(spec=widgets.ObjectIdSelect)
     cls.object1 = TestModel.objects.create(name="Test object 1")
     cls.object2 = TestModel.objects.create(name="Test object 2")
예제 #8
0
 def setUp(self):
     """
     Creates a new mock Image object for each test
     Sets a known name of the image
     """
     self.image = mock.MagicMock(spec=models.Image)
     self.image.name = 'gallery/foo.jpg'
 def setUp(self):
     """
     Creates a GalleryImageFieldFile object with known values
     for each test. Saves used mocks of the InMemoryImageData
     and ImageFile classes.
     """
     super().setUp()
     # patch classes used to manipulate with image data
     with mock.patch.object(image_data, 'InMemoryImageData') as m:
         with mock.patch.object(image_data, 'ImageFile') as f:
             # set known settings
             with patch_settings({
                     'image_width': 1024,
                     'image_height': 768,
                     'small_image_width': 800,
                     'small_image_height': 600,
                     'preview_width': 400,
                     'preview_height': 300,
                     'small_preview_width': 200,
                     'small_preview_height': 150,
                     'thumbnail_width': 120,
                     'thumbnail_height': 80
             }):
                 # create the object
                 self.field_file = fields.GalleryImageFieldFile(
                     self.image, mock.MagicMock(), str(self.image))
         # save mocks of called classes
         self.image_file = f
         self.in_memory_data = m
    def test_save_files_image_data_does_not_exist(self):
        """
        Checks whether save methods of image objects are
        called properly and the name has been set to the
        name in the database
        """
        # replace creation of the directory
        self.field_file._check_dir = mock.MagicMock()
        # data does not exist
        self.field_file.image_data.data = None
        # set known name in the database
        self.field_file.image_data.name_in_db = 'foo'
        # call the method with known arguments
        self.field_file.save_files('bar', 'baz')

        # check whether the _check_dir has been called
        self.field_file._check_dir.assert_called_with()
        # check whether the save methods of all image objects
        # has been called with the arguments passed to tested method
        self.field_file.image_data.save.assert_called_with(
            self.field_file, 'bar', 'baz')
        self.field_file.thumbnail.save.assert_called_with(
            self.field_file, 'bar', 'baz')
        self.field_file.preview.save.assert_called_with(
            self.field_file, 'bar', 'baz')
        self.field_file.small_preview.save.assert_called_with(
            self.field_file, 'bar', 'baz')
        self.field_file.small_image.save.assert_called_with(
            self.field_file, 'bar', 'baz')
        # check whether the name has been set to the name in the database
        self.assertEqual(self.field_file.name, 'foo')
예제 #11
0
 def test_get_formset(self):
     """
     Checks whether the formset has the 'preview_url_pattern'
     attribute containing the URL pattern
     """
     # the mock object returned by parent's method
     formset = mock.MagicMock()
     # patch parent class to return the mock
     with mock.patch(
         'django.contrib.contenttypes.admin'
         '.GenericInlineModelAdmin.get_formset',
         return_value=formset
         # patch the helper function to return known value
     ) as get_formset, mock.patch.object(
         utils,
         'get_admin_new_image_preview_url_pattern',
         return_value='url_pattern'
     ) as get_pattern:
         # call the method being tested with the mock ImageAdminInline
         result = admin.ImageAdminInline.get_formset(
             self.inline_admin,
             'request'
         )
         # check whether parent's method has been called
         # with the same argument
         get_formset.assert_called_with('request', None)
         # check whether the helper function has been called
         get_pattern.assert_called_with()
     # check whether the method returns the result of parent's method
     self.assertEqual(formset, result)
     # check whether the 'preview_url_pattern' of returned object
     # has the correct value
     self.assertEqual(formset.preview_url_pattern, 'url_pattern')
예제 #12
0
 def test_filter_choices(self):
     """
     Checks whether the _filter_choices method removes from
     the choices list all models unless it has the gallery_visible
     attribute with True value. Also an empty choice should remain
     """
     # create a choice of TestModel (gallery_visible=True)
     ctype = ContentType.objects.get_for_model(TestModel)
     test_choice = (str(ctype.pk), ctype.name)
     # create a choice of AnotherTestModel (gallery_visible=False)
     ctype = ContentType.objects.get_for_model(AnotherTestModel)
     another_choice = (str(ctype.pk), ctype.name)
     # create a choice of WrongTestModel (has not gallery_visible)
     ctype = ContentType.objects.get_for_model(WrongTestModel)
     wrong_choice = (str(ctype.pk), ctype.name)
     # create a mock widget object
     widget = mock.MagicMock(spec=widgets.ContentTypeSelect)
     # set initial choices
     widget.choices = [("", "----"), test_choice, another_choice,
                       wrong_choice]
     # call the _filter_choices method
     widgets.ContentTypeSelect._filter_choices(widget)
     # check whether an empty choice is in the list
     self.assertIn(("", "----"), widget.choices)
     # check whether the TestModel choice is in the list
     self.assertIn(test_choice, widget.choices)
     # check whether the AnotherTestModel choice is not in the list
     self.assertNotIn(another_choice, widget.choices)
     # check whether the WrongTestModel choice is not in the list
     self.assertNotIn(wrong_choice, widget.choices)
예제 #13
0
 def test_create_image_data(self):
     """
     Checks whether the create_image_data function returns
     correct data
     """
     # create a mock image with known values of the urls
     image = mock.MagicMock()
     image.image_url = 'foo'
     image.small_image_url = 'bar'
     # patch settings so that set known sizes
     with patch_settings({
             'image_width': 1024,
             'image_height': 768,
             'small_image_width': 800,
             'small_image_height': 600
     }):
         # call the create_image_data function
         data = utils.create_image_data(image)
     # check whether the full-size image URL is correct
     self.assertEqual(data['image']['url'], 'foo')
     # check whether the full-size image size is correct
     self.assertEqual(data['image']['width'], 1024)
     self.assertEqual(data['image']['height'], 768)
     # check whether the small image URL is correct
     self.assertEqual(data['small_image']['url'], 'bar')
     # check whether the small image size is correct
     self.assertEqual(data['small_image']['width'], 800)
     self.assertEqual(data['small_image']['height'], 600)
예제 #14
0
 def setUp(self):
     self.scrapy = ScrapyCtl(accounts={}, loglevel='ERROR')
     self.command = Command()
     self.command.stdout = mock.MagicMock()
     self.all_spiders = [
         'mangareader', 'unionmangas', 'kissmanga', 'batoto', 'mangahere',
         'mangafox', 'mangasee'
     ]
예제 #15
0
 def test_render_with_image(self, escape):
     """
     Checks whether the template_with_initial is filled properly
     if the render method has been called with saved image
     """
     # set initial template_with_initial value
     self.widget.template = "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}"
     # create a mock image field file object
     image = mock.MagicMock(spec=fields.GalleryImageFieldFile)
     # set known settings and patch helper functions
     with patch_settings({
             'preview_width': 400,
             'preview_height': 300,
     }), mock.patch.object(
             utils, 'create_image_data',
             return_value='data') as create_data, mock.patch.object(
                 utils, 'create_static_url',
                 return_value='url') as create_url, mock.patch.object(
                     AdminFileWidget,  # patch the parent's render method
                     'render',
                     return_value='foo') as render:
         # call the method with an image field file mock
         result = widgets.ImageWidget.render(self.widget, 'name', image)
         # check whether the parent's method has been called
         # with the same arguments
         render.assert_called_with('name', image, None)
         # check whether tha create_static_url helper function has been
         # called with the path to zoom image
         create_url.assert_called_with("content_gallery/img/zoom.png")
         # check whether the create_image_data helper function has been
         # called with the image filed file mock
         create_data.assert_called_with(image)
     # check whether the escape has been called with the returned by
     # create_image_data value in JSON format
     escape.assert_called_with(json.dumps('data'))
     # check whether the method returns the result of the parent's method
     self.assertEqual(result, 'foo')
     # check whether the template has been filled properly
     self.assertEqual(
         self.widget.template_with_initial,
         "\n".join([
             # the size of the container
             str(400 + 14),
             str(300 + 14),
             # the size of the image
             str(400),
             str(300),
             # the line-height
             str(300),
             # the result of the escape function
             "escaped data",
             # the result of create_static_url function
             "url",
             # the left offset of the zoom image
             str(400 - 55)
         ]))
예제 #16
0
    def test_get_mole_image_prediction_failed(self, mock_requests):
        post_mock = mock.MagicMock()
        post_mock.json.return_value = {
            'status': 'error',
        }
        mock_requests.post.return_value = post_mock

        # Task `get_mole_image_prediction` runs automatically on post save
        # signal
        with self.fake_media(), self.assertRaises(GetPredictionError):
            MoleImageFactory.create(photo=self.get_sample_image_file())
예제 #17
0
    def test_set_up(self, mock_requests):
        post_mock = mock.MagicMock()
        post_mock.json.return_value = {
            'status': 'success',
            'probability': 0.567,
            'prediction': 'Seems benign',
        }
        mock_requests.post.return_value = post_mock
        with self.fake_media():
            MoleImageFactory.create(photo=self.get_sample_image_file())

        self.assertTrue(mock_requests.post.called)
예제 #18
0
 def test_save_data_unchanged_image(self):
     """
     Checks whether saving data of an unchanged image does not call
     the _get_slug and _get_position methods
     """
     # use mocks for methods could be called
     self.image._get_slug = mock.MagicMock()
     self.image._get_position = mock.MagicMock()
     self.image.image.save_files = mock.MagicMock()
     self.image._object_changed = mock.MagicMock(return_value=False)
     # call the _save_data method
     self.image._save_data()
     # check whether the _get_slug and _get_position methods
     # has not been called
     self.image._get_slug.assert_not_called()
     self.image._get_position.assert_not_called()
     # get a name of the image
     name = self.get_name('foo.jpg')
     # check whether the save_files method of the image field
     # has been called with empty slug and the name of the image
     self.image.image.save_files.assert_called_once_with('', name)
예제 #19
0
 def test_delete_files_image(self):
     """
     Checks whether the delete_files method calls the delete_files
     method of the image field
     """
     # set a mock to the method could be called
     self.image.image.delete_files = mock.MagicMock()
     # call the delete_files method
     self.image.delete_files()
     # check whether the delete_files method of the image field
     # has been called
     self.image.image.delete_files.assert_called_once_with()
예제 #20
0
 def test_delete(self):
     """
     Tests whether the delete method calls the delete_files
     methods of all contained objects
     """
     # create two mock objects
     obj1 = mock.MagicMock()
     obj2 = mock.MagicMock()
     # create a mock query set object
     query_set = mock.MagicMock(spec=models.ImageQuerySet)
     # the query set iteration yields objects created before
     query_set.__iter__.return_value = [obj1, obj2]
     # patch the delete method of the parent class
     with mock.patch('django.db.models.QuerySet.delete') as delete:
         # call the delete method
         models.ImageQuerySet.delete(query_set)
         # check whether the parent's delete method has been called
         delete.assert_called_with()
     # check whether the delete_files methods
     # of both objects have been called
     obj1.delete_files.assert_called_with()
     obj2.delete_files.assert_called_with()
예제 #21
0
 def test_save_data_changed_image(self):
     """
     Checks whether saving data of a changed image creates a new slug
     and sets a position
     """
     # use mocks for methods could be called
     self.image._get_slug = mock.MagicMock(return_value='foo')
     self.image._get_position = mock.MagicMock()
     self.image.image.save_files = mock.MagicMock()
     # object_changed should return True
     self.image._object_changed = mock.MagicMock(return_value=True)
     # call the _save_data method
     self.image._save_data()
     # check whether the _get_slug and the _get_position methods
     # have been called
     self.image._get_slug.assert_called_once_with()
     self.image._get_position.assert_called_once_with()
     # get a name of the image
     name = self.get_name('foo.jpg')
     # check whether the save_files method of the image field
     # has been called with a new slug and the name of the image
     self.image.image.save_files.assert_called_once_with('foo', name)
예제 #22
0
 def test_small_preview_url_property(self):
     """
     Checks whether the small_preview_url property returns a result
     of the small_preview_url property of the image field
     """
     # mock the image field and set the small_preview_url value
     image_mock = mock.MagicMock()
     image_mock.small_preview_url = 'foo'
     # patch the image object
     with mock.patch.object(self.image, 'image', image_mock):
         # check whether the small_preview_url property returns
         # a value of the small_preview_url of the mock
         self.assertEqual(self.image.small_preview_url, 'foo')
예제 #23
0
파일: tests.py 프로젝트: YahooG/python
    def test_cursor_close_failure_does_not_mask_original_exception(self):
        persons = Person.objects.iterator()

        def raise_original_exception(*args, **kwargs):
            raise Exception(
                'Real exception raised by the database on cursor.execute')

        def raise_close_exception():
            raise Exception(
                'Error when attempting to close the cursor, this exception should not mask the original exception'
            )

        mock_cursor = connection.chunked_cursor()
        mock_cursor.execute = mock.MagicMock(
            side_effect=raise_original_exception)
        mock_cursor.close = mock.MagicMock(side_effect=raise_close_exception)

        with self.assertRaisesMessage(
                Exception,
                'Real exception raised by the database on cursor.execute'):
            with mock.patch('django.db.connection.create_cursor',
                            return_value=mock_cursor):
                list(persons)
예제 #24
0
    def test_get_mole_image_prediction_success(self, mock_requests):
        post_mock = mock.MagicMock()
        post_mock.json.return_value = {
            'status': 'success',
            'probability': 0.567,
            'prediction': 'Seems benign',
        }
        mock_requests.post.return_value = post_mock

        # Task `get_mole_image_prediction` runs automatically on post save
        # signal
        with self.fake_media():
            mole_image = MoleImageFactory.create(
                photo=self.get_sample_image_file())

        mole_image.refresh_from_db()
        self.assertEqual(mole_image.prediction, 'Seems benign')
        self.assertAlmostEqual(float(mole_image.prediction_accuracy), 0.567)
 def test_filename_property(self):
     """
     Checks whether the filename property returns a result of
     the _create_filename method called with the name as an argument
     """
     # set a name
     self.image_file.name = 'bar'
     # create a mock for the method
     mock_func = mock.MagicMock(return_value='foo')
     # set the mock to the _create_filename attribute
     self.image_file._create_filename = mock_func
     # check whether the property returns a result of 
     # the _create_filename method
     self.assertEqual(
         image_data.ImageFile.filename.fget(self.image_file),
         'foo'
     )
     # check whether the _create_filename method has been called
     # with the name as an argument
     mock_func.assert_called_with('bar')
예제 #26
0
 def test_render_with_uploaded_image(self):
     """
     Checks whether the template_with_initial is not affected by
     the render method if it has been called with just uploaded image
     """
     # set initial template_with_initial value
     self.widget.template_with_initial = "bar"
     # create a mock object of just uploaded image
     image = mock.MagicMock(spec=InMemoryUploadedFile)
     # patch the parent's render method
     with mock.patch.object(AdminFileWidget, 'render',
                            return_value='foo') as render:
         # call the method with just uploaded image mock
         result = widgets.ImageWidget.render(self.widget, 'name', image)
         # check whether the parent's method has been called
         # with the same arguments
         render.assert_called_with('name', image, None)
     # check whether the method returns the result of the parent's method
     self.assertEqual(result, 'foo')
     # check whether the template_with_initial has not been changed
     self.assertEqual(self.widget.template_with_initial, 'bar')
예제 #27
0
 def setUp(self):
     """
     Creates a mock widget object
     """
     self.widget = mock.MagicMock(spec=widgets.ImageInlineWidget)
예제 #28
0
 def setUp(self):
     """
     Creates a mock object passed to methods of 
     the ImageAdminInline for each test
     """
     self.inline_admin = mock.MagicMock(spec=admin.ImageAdminInline)
 def setUp(self):
     """
     Creates a new mock InMemoryImageData object for each test
     """
     super().setUp()
     self.memory_data = mock.MagicMock(spec=image_data.InMemoryImageData)
 def setUp(self):
     """
     Creates a new mock ImageFile object for each test
     """
     super().setUp()
     self.image_file = mock.MagicMock(spec=image_data.ImageFile)