Coverage for tests/test_image_utils.py: 100%

46 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-08-09 04:47 +0000

1#!/usr/bin/env python3 

2 

3import os 

4 

5from unittest import TestCase 

6 

7from io import BytesIO 

8 

9from image_utils import img_to_base64 

10from image_utils import img_to_bytesio 

11from image_utils import base64_to_img 

12 

13from media_utils import get_image_file_info 

14 

15from PIL import Image 

16 

17 

18class TestImageUtils(TestCase): 

19 

20 def test_base64(self) -> None: 

21 image = Image.new('RGB', (64, 48), color='red') 

22 

23 base64_str = img_to_base64(image) 

24 self.assertIsInstance(base64_str, str) 

25 assert isinstance(base64_str, str) # narrow Optional[str] to str for mypy 

26 

27 image_from_base64 = base64_to_img(base64_str) 

28 self.assertIsInstance(image_from_base64, Image.Image) 

29 self.assertEqual(image.size, image_from_base64.size) 

30 

31 base64_str = img_to_base64(None) 

32 self.assertIsNone(base64_str) 

33 

34 image_bytesio = img_to_bytesio(image) 

35 self.assertIsInstance(image_bytesio, BytesIO) 

36 image_bytesio = img_to_bytesio(None) 

37 self.assertIsNone(image_bytesio) 

38 

39 image_path = "test_image.png" 

40 with open(image_path, "wb") as f: 

41 image.save(f, format="PNG") 

42 image_info = get_image_file_info(image_path) 

43 self.assertEqual(image_info['width'], 64) 

44 self.assertEqual(image_info['height'], 48) 

45 self.assertAlmostEqual(image_info['aspect_ratio'], 4.0 / 3.0, delta=0.1) 

46 

47 with self.assertRaises(TypeError): 

48 img_to_base64(12345) # type: ignore[arg-type] 

49 with self.assertRaises(TypeError): 

50 base64_to_img(12345) # type: ignore[arg-type] 

51 with self.assertRaises(Exception): 

52 base64_to_img("not-a-real-base64-string") 

53 with self.assertRaises(TypeError): 

54 img_to_bytesio(12345) # type: ignore[arg-type] 

55 with self.assertRaises(FileNotFoundError): 

56 get_image_file_info("non_existent_file.png") 

57 with self.assertRaises(TypeError): 

58 get_image_file_info(["list", "of", "files"]) # type: ignore[arg-type] 

59 

60 os.remove(image_path) 

61 del image 

62 del base64_str 

63 del image_from_base64