17
17
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
18
#
19
19
20
+ from contextlib import contextmanager
20
21
from openslide import ImageSlide , OpenSlideError
21
22
from PIL import Image
22
23
import unittest
25
26
26
27
# Tests should be written to be compatible with Python 2.6 unittest.
27
28
29
+ @contextmanager
30
+ def image_open (* args , ** kwargs ):
31
+ img = Image .open (* args , ** kwargs )
32
+ try :
33
+ yield img
34
+ finally :
35
+ if hasattr (img , 'close' ):
36
+ # Pillow >= 2.5.0
37
+ img .close ()
38
+
39
+
28
40
class TestImageWithoutOpening (unittest .TestCase ):
29
41
def test_detect_format (self ):
30
42
self .assertTrue (
@@ -41,19 +53,19 @@ def test_open(self):
41
53
lambda : ImageSlide (file_path ('../setup.py' )))
42
54
43
55
# passing PIL.Image to ImageSlide
44
- self . assertEqual (
45
- ImageSlide (Image . open ( file_path ( 'boxes.png' ))). dimensions ,
46
- (300 , 250 ))
56
+ with image_open ( file_path ( 'boxes.png' )) as img :
57
+ with ImageSlide (img ) as osr :
58
+ self . assertEqual ( osr . dimensions , (300 , 250 ))
47
59
48
60
def test_operations_on_closed_handle (self ):
49
- img = Image . open (file_path ('boxes.png' ))
50
- osr = ImageSlide (img )
51
- osr .close ()
52
- self .assertRaises (AttributeError ,
53
- lambda : osr .read_region ((0 , 0 ), 0 , (100 , 100 )))
54
- # If an Image is passed to the constructor, ImageSlide.close()
55
- # shouldn't close it
56
- self .assertEqual (img .getpixel ((0 , 0 )), 3 )
61
+ with image_open (file_path ('boxes.png' )) as img :
62
+ osr = ImageSlide (img )
63
+ osr .close ()
64
+ self .assertRaises (AttributeError ,
65
+ lambda : osr .read_region ((0 , 0 ), 0 , (100 , 100 )))
66
+ # If an Image is passed to the constructor, ImageSlide.close()
67
+ # shouldn't close it
68
+ self .assertEqual (img .getpixel ((0 , 0 )), 3 )
57
69
58
70
def test_context_manager (self ):
59
71
osr = ImageSlide (file_path ('boxes.png' ))
0 commit comments