Skip to content

Commit

Permalink
ImageDimensionBear: Add image dimension bear
Browse files Browse the repository at this point in the history
Added ImageDimensionBear.py in bears/general, that runs
the gem img_checker to see if images follow given
dimensions by user.
Also added unittest for the bear, ImageDimensionBearTest.py
in tests/general

Closes #1260
  • Loading branch information
rhemon committed Jun 14, 2017
1 parent 0650689 commit 8fa3242
Show file tree
Hide file tree
Showing 6 changed files with 194 additions and 0 deletions.
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ ruby '2.2.2'

gem "csvlint"
gem "puppet-lint", "2.1.1"
gem "img_checker"
gem "reek"
gem "rubocop", "0.47.1"
gem "scss_lint", require: false
Expand Down
96 changes: 96 additions & 0 deletions bears/general/ImageDimensionBear.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
from glob import glob
import os
import yaml
import shutil

from coalib.bears.GlobalBear import GlobalBear
from coalib.results.Result import Result
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
from dependency_management.requirements.GemRequirement import GemRequirement
from dependency_management.requirements.PipRequirement import PipRequirement
from sarge import run, Capture


def check_path(image_file):
if (glob(str(image_file)) == []):
raise ValueError('Provide a correct path for image')
else:
return os.path.join('..', str(image_file))


def check_width(width):
if (int(width) <= 0):
raise ValueError('Width has to be greater than 0')

else:
return int(width)


def check_height(height):
if (int(height) <= 0):
raise ValueError('Height has to be greater than 0')
else:
return int(height)


class ImageDimensionBear(GlobalBear):
"""
Checks the dimension of an image us a gem.
More information is available at <github.com/Abhi2424shek/img_checker>
"""

AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'[email protected]'}
REQUIREMENTS = {GemRequirement('img_checker'),
PipRequirement('pyyaml', '3.12')}
LICENSE = 'AGPL-3.0'
CAN_FIX = {'Image Dimension'}

@classmethod
def check_prerequisites(cls):
if shutil.which('img_checker') is None:
return 'img_checker is not installed.'
return True

def run(self,
image_file: check_path,
width: check_width,
height: check_height):
"""
This bear ensures that images used in your project are
within a fixed dimension.
WARNING: If your repository has an existing img_config.yml
file, please change it since this bear creates a file
with that name and removes it in the end.
:param image_file: The file/directory that bear
will look for images
:param width: The maximum width value allowed
for images
:param height: The maximum height value allowed
for images
"""
# self.warn(warning_message)
os.mkdir('temp_dir_for_img_config_file')
os.chdir('temp_dir_for_img_config_file')
with open('img_config.yml', 'w') as yaml_file:
config = [{'directory': image_file,
'width': width,
'height': height}]
yaml.dump(config, yaml_file, default_flow_style=False)
self.debug(glob(image_file))
cmd = 'img_checker'
output = run(cmd, stdout=Capture(), stderr=Capture())
os.remove('img_config.yml')
os.chdir('..')
os.rmdir('temp_dir_for_img_config_file')
if (output.returncode):
lines = output.stdout.text.split('\n')[1:-2]
for line in lines:
line = line[0:line.index('image')+6] + \
line[line.index('image')+9:]
yield Result(origin=self,
message=line,
severity=RESULT_SEVERITY.MAJOR)
6 changes: 6 additions & 0 deletions test-img/.coafile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[Default]
bears = ImageDimensionBear
files = .coafile
image_file = ./test-img/*.*
width = 240
height = 240
Binary file added test-img/images.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added test-img/img.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
91 changes: 91 additions & 0 deletions tests/general/ImageDimensionBearTest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import unittest
from unittest.case import skip, skipIf
from queue import Queue
import shutil

from bears.general.ImageDimensionBear import *
from coalib.output.printers.LOG_LEVEL import LOG_LEVEL
from coalib.settings.Section import Section
from coalib.settings.Setting import Setting
from coalib.testing.BearTestHelper import generate_skip_decorator


@generate_skip_decorator(ImageDimensionBear)
class ImageDimensionBearTest(unittest.TestCase):
"""
Runs unittests for ImageDimensionBear
"""

def setUp(self):
self.section = Section('')
self.queue = Queue()
self.file_dict = {}
self.idb = ImageDimensionBear(None, self.section, self.queue)

def test_check_width(self):
with self.assertRaisesRegexp(ValueError, 'Width'):
check_width('-12')
self.assertEqual(check_width('120'), 120)

def test_check_height(self):
with self.assertRaisesRegexp(ValueError, 'Height'):
check_height('-12')
self.assertEqual(check_height('120'), 120)

def test_check_path(self):
with self.assertRaisesRegexp(ValueError, 'Provide'):
check_path('test-image/')
self.assertEqual(check_path('test-img/'), '../test-img/')

def test_check_prerequisites(self):
_shutil_which = shutil.which
try:
shutil.which = lambda *args, **kwargs: None
self.assertEqual(ImageDimensionBear.check_prerequisites(),
'img_checker is not installed.')

shutil.which = lambda *args, **kwargs: 'path/to/bundle'
self.assertTrue(ImageDimensionBear.check_prerequisites())
finally:
shutil.which = _shutil_which

def test_run_with_png(self):
path = os.path.join('..', 'test-img', '*.png')
message = ('The image test-img/img.png is larger'
' than 240px x 240px [w x h]')
result = next(self.idb.run(
image_file=path,
width=240,
height=240))
self.assertEqual(message,
result.message)

def test_run_with_jpg(self):
path = os.path.join('..', 'test-img', '*.jpg')
self.assertEqual([],
list(self.idb.run(
image_file=path,
width=240,
height=240)))

def test_run_with_jpg_fail(self):
path = os.path.join('..', 'test-img', '*.jpg')
message = ('The image test-img/images.jpg is larger'
' than 50px x 50px [w x h]')
result = next(self.idb.run(
image_file=path,
width=50,
height=50))
self.assertEqual(message,
result.message)

def test_run_with_both(self):
path = os.path.join('..', 'test-img', '*.*')
message = ('\w* \w+-\w+\/\w+\.\w+ is larger'
' than 50px x 50px \[w x h]')
output = str(list(self.idb.run(
image_file=path,
width=50,
height=50)))
self.assertRegex(output,
message)

0 comments on commit 8fa3242

Please sign in to comment.