Skip to content

Commit 901d0ac

Browse files
Add model tests.
1 parent 2a6cc87 commit 901d0ac

File tree

3 files changed

+44
-6
lines changed

3 files changed

+44
-6
lines changed

ets_tutorial/__init__.py

Whitespace-only changes.

stage4.1_first_application/pycasa/model/image_file.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,33 @@
44
import numpy as np
55

66
# ETS imports
7-
from traits.api import Dict, File, HasStrictTraits, observe
7+
from traits.api import cached_property, Dict, File, HasStrictTraits, Property
88

99

1010
class ImageFile(HasStrictTraits):
1111
""" Model to hold an image file.
1212
"""
1313
filepath = File
1414

15-
metadata = Dict
15+
metadata = Property(Dict, depends_on="filepath")
1616

1717
def to_array(self):
18+
if not self.filepath:
19+
return np.array([])
20+
1821
with PIL.Image.open(self.filepath) as img:
1922
return np.asarray(img)
2023

21-
@observe("filepath")
22-
def load_metadata(self, event):
24+
@cached_property
25+
def _get_metadata(self):
26+
if not self.filepath:
27+
return {}
28+
2329
with PIL.Image.open(self.filepath) as img:
2430
exif = img._getexif()
2531

2632
if exif:
27-
self.metadata = {TAGS[k]: v for k, v in exif.items()
28-
if k in TAGS}
33+
return {TAGS[k]: v for k, v in exif.items()
34+
if k in TAGS}
35+
else:
36+
return {}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from os.path import dirname, join
2+
from unittest import TestCase
3+
4+
import numpy as np
5+
from numpy.testing import assert_array_equal
6+
7+
from pycasa.model.image_file import ImageFile
8+
9+
import ets_tutorial
10+
11+
TUTORIAL_DIR = dirname(ets_tutorial.__file__)
12+
13+
SAMPLE_IMG_DIR = join(TUTORIAL_DIR, "..", "sample_images")
14+
15+
SAMPLE_IMG1 = join(SAMPLE_IMG_DIR, "IMG-0311_xmas_2020.JPG")
16+
17+
18+
class TestImageFile(TestCase):
19+
def test_no_image_file(self):
20+
img = ImageFile()
21+
self.assertEqual(img.metadata, {})
22+
data = img.to_array()
23+
self.assertIsInstance(data, np.ndarray)
24+
self.assertEqual(data.shape, (0,))
25+
26+
def test_image_metadata(self):
27+
img = ImageFile(filepath=SAMPLE_IMG1)
28+
self.assertNotEqual(img.metadata, {})
29+
data = img.to_array()
30+
self.assertEqual(data.shape, (768, 1024, 3))

0 commit comments

Comments
 (0)