Python Forum
I have 'Failed: DID NOT RAISE <class 'Exception'>'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I have 'Failed: DID NOT RAISE <class 'Exception'>'
#1
code test.py:
import pytest

#################### PHASE 1 ####################

def test_imports():
    from pixel import Pixel
    from image import Image
    from encoding import Encoder, Decoder

def test_pixel_no_negative():
    from pixel import Pixel
    with pytest.raises(Exception):
        B = Pixel(0, 0xFF, -1)

def test_pixel_eq():
    from pixel import Pixel
    RED = Pixel(0xFF, 0, 0)
    GREEN = Pixel(0, 0xFF, 0)
    BLUE = Pixel(0, 0, 0xFF)
    RED2 = Pixel(0xFF, 0, 0)
    assert RED == RED2

def test_pixel_neq():
    from pixel import Pixel
    RED = Pixel(0xFF, 0, 0)
    GREEN = Pixel(0, 0xFF, 0)
    BLUE = Pixel(0, 0, 0xFF)
    assert RED != GREEN
    assert GREEN != BLUE
    assert RED != BLUE

def test_image_init_raises_exception():
    from pixel import Pixel
    from image import Image
    with pytest.raises(Exception):
        Image(4, 4, [Pixel(0, 0, 0)])
    with pytest.raises(Exception):
        Image(1, 1, [(0, 0, 0)])

def test_image_getitem():
    from image import Image
    from pixel import Pixel
    BLACK = Pixel(0x00, 0x00, 0x00)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    img = Image(2, 1, [BLACK, WHITE])
    assert img[0,0] == BLACK
    assert img[1,0] == WHITE

def test_image_setitem():
    from pixel import Pixel
    from image import Image
    BLACK = Pixel(0x00, 0x00, 0x00)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    img = Image(3, 1, [BLACK, WHITE, BLACK])
    img[0,0] = WHITE
    assert img[0,0] == img[1,0] == WHITE
    assert img[2,0] == BLACK

def test_image_setitem_raises_indexerror():
    from pixel import Pixel
    from image import Image
    img = Image(1, 1, [Pixel(0, 0, 0)])
    with pytest.raises(IndexError):
        img[1,1] = Pixel(0, 0xFF, 0)

def test_img_eq():
    from pixel import Pixel
    from image import Image
    BLACK = Pixel(0x00, 0x00, 0x00)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    img1 = Image(3, 1, [BLACK, WHITE, BLACK])
    img2 = Image(3, 1, [BLACK, WHITE, BLACK])
    assert img1 == img2

def test_img_neq():
    from pixel import Pixel
    from image import Image
    BLACK = Pixel(0x00, 0x00, 0x00)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    img1 = Image(3, 1, [BLACK, WHITE, BLACK])
    img2 = Image(3, 1, [BLACK, BLACK, BLACK])
    assert img1 != img2

def _get_squares_img():
    from pixel import Pixel
    from image import Image
    BLACK = Pixel(0, 0, 0)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    return Image(2, 2, [BLACK, WHITE, BLACK, WHITE])

def _get_file_content(path: str):
    return open(path, 'rb').read()

def _set_file_content(path: str, content: bytes):
    open(path, 'wb').write(content)

def _get_tempfile():
    import tempfile
    return tempfile.mktemp()

def _image_as_bytes(image, *args, **kwargs):
    from encoding import Encoder
    path = _get_tempfile()
    Encoder(image, *args, **kwargs).save_to(path)
    return _get_file_content(path)

def _bytes_as_img(b):
    from encoding import Decoder
    path = _get_tempfile()
    _set_file_content(path, b)
    return Decoder.load_from(path)

SQUARES_ULBMP1_CONTENT = bytes.fromhex('554c424d50010c0002000200000000ffffff000000ffffff')

def test_encode_squares_ulbmp1():
    assert _image_as_bytes(_get_squares_img()) == SQUARES_ULBMP1_CONTENT

def test_decode_squares_ulbmp1():
    assert _bytes_as_img(SQUARES_ULBMP1_CONTENT) == _get_squares_img()

def test_load_from_corrupt():
    bad_content = b'ULBPM\x01\x08\x00'
    with pytest.raises(Exception):
        _bytes_as_img(bad_content)

def test_load_from_incomplete():
    incomplete_content = b'ULBMP\x01\x0c\x00\x02\x00\x02\x00\x00\x00\x00'
    with pytest.raises(Exception):
        _bytes_as_img(incomplete_content)
work to be done:
however without changing the code test.py, codes the scripts encoding, image and pixel so when performing 'pytest test.py' there is no error.

my pixel.py:
class Pixel:
    def __init__(self, red: int, green: int, blue: int):
        if not all(0 <= c <= 255 for c in (red, green, blue)):
            raise Exception("RGB values must be between 0 and 255")
        self._red = red
        self._green = green
        self._blue = blue

    @property
    def red(self):
        return self._red

    @property
    def green(self):
        return self._green

    @property
    def blue(self):
        return self._blue

    def __eq__(self, other):
        if not isinstance(other, Pixel):
            return False
        return self._red == other._red and self._green == other._green and self._blue == other._blue
my encoding.py:
from image import Image
from pixel import Pixel
class Encoder:
    def __init__(self, img: Image):
        self._img = img

    def save_to(self, path: str) -> None:
        with open(path, 'wb') as f:
            f.write(b'ULBMP')
            f.write(b'\x01')  # Version 1
            header_size = 12
            f.write(header_size.to_bytes(2, 'little'))
            f.write(self._img._width.to_bytes(2, 'little'))
            f.write(self._img._height.to_bytes(2, 'little'))

            for pixel in self._img._pixels:
                f.write(bytes([pixel.red, pixel.green, pixel.blue]))

class Decoder:
    @staticmethod
    def load_from(path: str) -> Image:
        with open(path, 'rb') as f:
            signature = f.read(5)
            if signature != b'ULBMP':
                raise Exception("Invalid ULBMP file")
            version = int.from_bytes(f.read(1), 'little')
            if version != 1:
                raise Exception(f"Unsupported ULBMP version: {version}")
            header_size = int.from_bytes(f.read(2), 'little')
            width = int.from_bytes(f.read(2), 'little')
            height = int.from_bytes(f.read(2), 'little')
            pixels = []
            for _ in range(width * height):
                red = int.from_bytes(f.read(1), 'little')
                green = int.from_bytes(f.read(1), 'little')
                blue = int.from_bytes(f.read(1), 'little')
                pixels.append(Pixel(red, green, blue))
            if len(pixels) != width * height:
                raise Exception("Incomplete ULBMP file")
            return Image(width, height, pixels)
my image.py:
from pixel import Pixel
class Image:
    def __init__(self, _width: int, _height: int, _pixels: list):
        if _width <= 0 or _height <= 0:
            raise Exception("Les dimensions de l'image doivent être des entiers positifs")
        if len(_pixels) != _width * _height:
            raise Exception("La liste de pixels ne correspond pas aux dimensions de l'image")
        self._width = _width
        self._height = _height
        self._pixels = _pixels

    def __getitem__(self, pos: tuple[int,int]) -> Pixel:
        x, y = pos
        if not (0 <= x < self._width and 0 <= y < self._height):
            raise IndexError("Position out of bounds")
        return self._pixels[y * self._width + x]

    def __setitem__(self, pos: tuple[int,int], pix: Pixel) -> None:
        x, y = pos
        if not (0 <= x < self._width and 0 <= y < self._height):
            raise IndexError("Position out of bounds")
        self._pixels[y * self._width + x] = pix

    def __eq__(self, other: 'Image') -> bool:
        if not isinstance(other, Image):
            return False
        return (self._width, self._height, self._pixels) == (other._width, other._height, other._pixels)
but when I do pytest test.py I have the following errors:
Error:
batchayw@batchayw-Precision-5520:~/Téléchargements/Yassin/phase1$ pytest test.py ============================= test session starts ============================== platform linux -- Python 3.10.12, pytest-8.0.1, pluggy-1.4.0 rootdir: /home/batchayw/Téléchargements/Yassin/phase1 plugins: anyio-4.2.0 collected 14 items test.py ....F........F [100%] =================================== FAILURES =================================== _______________________ test_image_init_raises_exception _______________________ def test_image_init_raises_exception(): from pixel import Pixel from image import Image with pytest.raises(Exception): Image(4, 4, [Pixel(0, 0, 0)]) > with pytest.raises(Exception): E Failed: DID NOT RAISE <class 'Exception'> test.py:37: Failed __________________________ test_load_from_incomplete ___________________________ def test_load_from_incomplete(): incomplete_content = b'ULBMP\x01\x0c\x00\x02\x00\x02\x00\x00\x00\x00' > with pytest.raises(Exception): E Failed: DID NOT RAISE <class 'Exception'> test.py:128: Failed =========================== short test summary info ============================ FAILED test.py::test_image_init_raises_exception - Failed: DID NOT RAISE <class 'Exception'> FAILED test.py::test_load_from_incomplete - Failed: DID NOT RAISE <class 'Exception'> ========================= 2 failed, 12 passed in 0.11s ========================= batchayw@batchayw-Precision-5520:~/Téléchargements/Yassin/phase1$
Larz60+ write Feb-20-2024, 03:59 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
tags added for you this time. Please use BBCode tags on future posts.
Reply
#2
code test.py:
import pytest

#################### PHASE 1 ####################

def test_imports():
    from pixel import Pixel
    from image import Image
    from encoding import Encoder, Decoder

def test_pixel_no_negative():
    from pixel import Pixel
    with pytest.raises(Exception):
        B = Pixel(0, 0xFF, -1)

def test_pixel_eq():
    from pixel import Pixel
    RED = Pixel(0xFF, 0, 0)
    GREEN = Pixel(0, 0xFF, 0)
    BLUE = Pixel(0, 0, 0xFF)
    RED2 = Pixel(0xFF, 0, 0)
    assert RED == RED2

def test_pixel_neq():
    from pixel import Pixel
    RED = Pixel(0xFF, 0, 0)
    GREEN = Pixel(0, 0xFF, 0)
    BLUE = Pixel(0, 0, 0xFF)
    assert RED != GREEN
    assert GREEN != BLUE
    assert RED != BLUE

def test_image_init_raises_exception():
    from pixel import Pixel
    from image import Image
    with pytest.raises(Exception):
        Image(4, 4, [Pixel(0, 0, 0)])
    with pytest.raises(Exception):
        Image(1, 1, [(0, 0, 0)])

def test_image_getitem():
    from image import Image
    from pixel import Pixel
    BLACK = Pixel(0x00, 0x00, 0x00)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    img = Image(2, 1, [BLACK, WHITE])
    assert img[0,0] == BLACK
    assert img[1,0] == WHITE

def test_image_setitem():
    from pixel import Pixel
    from image import Image
    BLACK = Pixel(0x00, 0x00, 0x00)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    img = Image(3, 1, [BLACK, WHITE, BLACK])
    img[0,0] = WHITE
    assert img[0,0] == img[1,0] == WHITE
    assert img[2,0] == BLACK

def test_image_setitem_raises_indexerror():
    from pixel import Pixel
    from image import Image
    img = Image(1, 1, [Pixel(0, 0, 0)])
    with pytest.raises(IndexError):
        img[1,1] = Pixel(0, 0xFF, 0)

def test_img_eq():
    from pixel import Pixel
    from image import Image
    BLACK = Pixel(0x00, 0x00, 0x00)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    img1 = Image(3, 1, [BLACK, WHITE, BLACK])
    img2 = Image(3, 1, [BLACK, WHITE, BLACK])
    assert img1 == img2

def test_img_neq():
    from pixel import Pixel
    from image import Image
    BLACK = Pixel(0x00, 0x00, 0x00)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    img1 = Image(3, 1, [BLACK, WHITE, BLACK])
    img2 = Image(3, 1, [BLACK, BLACK, BLACK])
    assert img1 != img2

def _get_squares_img():
    from pixel import Pixel
    from image import Image
    BLACK = Pixel(0, 0, 0)
    WHITE = Pixel(0xFF, 0xFF, 0xFF)
    return Image(2, 2, [BLACK, WHITE, BLACK, WHITE])

def _get_file_content(path: str):
    return open(path, 'rb').read()

def _set_file_content(path: str, content: bytes):
    open(path, 'wb').write(content)

def _get_tempfile():
    import tempfile
    return tempfile.mktemp()

def _image_as_bytes(image, *args, **kwargs):
    from encoding import Encoder
    path = _get_tempfile()
    Encoder(image, *args, **kwargs).save_to(path)
    return _get_file_content(path)

def _bytes_as_img(b):
    from encoding import Decoder
    path = _get_tempfile()
    _set_file_content(path, b)
    return Decoder.load_from(path)

SQUARES_ULBMP1_CONTENT = bytes.fromhex('554c424d50010c0002000200000000ffffff000000ffffff')

def test_encode_squares_ulbmp1():
    assert _image_as_bytes(_get_squares_img()) == SQUARES_ULBMP1_CONTENT

def test_decode_squares_ulbmp1():
    assert _bytes_as_img(SQUARES_ULBMP1_CONTENT) == _get_squares_img()

def test_load_from_corrupt():
    bad_content = b'ULBPM\x01\x08\x00'
    with pytest.raises(Exception):
        _bytes_as_img(bad_content)

def test_load_from_incomplete():
    incomplete_content = b'ULBMP\x01\x0c\x00\x02\x00\x02\x00\x00\x00\x00'
    with pytest.raises(Exception):
        _bytes_as_img(incomplete_content)
work to be done:
however without changing the code test.py, codes the scripts encoding, image and pixel so when performing 'pytest test.py' there is no error.

my pixel.py:
class Pixel:
    def __init__(self, red: int, green: int, blue: int):
        if not all(0 <= c <= 255 for c in (red, green, blue)):
            raise Exception("RGB values must be between 0 and 255")
        self._red = red
        self._green = green
        self._blue = blue

    @property
    def red(self):
        return self._red

    @property
    def green(self):
        return self._green

    @property
    def blue(self):
        return self._blue

    def __eq__(self, other):
        if not isinstance(other, Pixel):
            return False
        return self._red == other._red and self._green == other._green and self._blue == other._blue
my encoding.py:
from image import Image
from pixel import Pixel

class Encoder:
    def __init__(self, img: Image):
        self._img = img

    def save_to(self, path: str) -> None:
        with open(path, 'wb') as f:
            f.write(b'ULBMP')
            f.write(b'\x01')  # Version 1
            header_size = 12
            f.write(header_size.to_bytes(2, 'little'))
            f.write(self._img._width.to_bytes(2, 'little'))
            f.write(self._img._height.to_bytes(2, 'little'))

            for pixel in self._img._pixels:
                f.write(bytes([pixel.red, pixel.green, pixel.blue]))

class Decoder:
    @staticmethod
    def load_from(path: str) -> Image:
        with open(path, 'rb') as f:
            signature = f.read(5)
            if signature != b'ULBMP':
                raise Exception("Invalid ULBMP file")
            version = int.from_bytes(f.read(1), 'little')
            if version != 1:
                raise Exception(f"Unsupported ULBMP version: {version}")
            header_size = int.from_bytes(f.read(2), 'little')
            width = int.from_bytes(f.read(2), 'little')
            height = int.from_bytes(f.read(2), 'little')
            pixels = []
            for _ in range(width * height):
                red = int.from_bytes(f.read(1), 'little')
                green = int.from_bytes(f.read(1), 'little')
                blue = int.from_bytes(f.read(1), 'little')
                pixels.append(Pixel(red, green, blue))
            if len(pixels) != width * height:
                raise Exception("Incomplete ULBMP file")
            return Image(width, height, pixels)
my image.py:
from pixel import Pixel

class Image:
    def __init__(self, _width: int, _height: int, _pixels: list):
        if _width <= 0 or _height <= 0:
            raise Exception("Les dimensions de l'image doivent être des entiers positifs")
        if len(_pixels) != _width * _height:
            raise Exception("La liste de pixels ne correspond pas aux dimensions de l'image")
        self._width = _width
        self._height = _height
        self._pixels = _pixels

    def __getitem__(self, pos: tuple[int,int]) -> Pixel:
        x, y = pos
        if not (0 <= x < self._width and 0 <= y < self._height):
            raise IndexError("Position out of bounds")
        return self._pixels[y * self._width + x]

    def __setitem__(self, pos: tuple[int,int], pix: Pixel) -> None:
        x, y = pos
        if not (0 <= x < self._width and 0 <= y < self._height):
            raise IndexError("Position out of bounds")
        self._pixels[y * self._width + x] = pix

    def __eq__(self, other: 'Image') -> bool:
        if not isinstance(other, Image):
            return False
        return (self._width, self._height, self._pixels) == (other._width, other._height, other._pixels)
but when I do pytest test.py I have the following errors:
Error:
batchayw@batchayw-Precision-5520:~/Téléchargements/Yassin/phase1$ pytest test.py ============================= test session starts ============================== platform linux -- Python 3.10.12, pytest-8.0.1, pluggy-1.4.0 rootdir: /home/batchayw/Téléchargements/Yassin/phase1 plugins: anyio-4.2.0 collected 14 items test.py ....F........F [100%] =================================== FAILURES =================================== _______________________ test_image_init_raises_exception _______________________ def test_image_init_raises_exception(): from pixel import Pixel from image import Image with pytest.raises(Exception): Image(4, 4, [Pixel(0, 0, 0)]) > with pytest.raises(Exception): E Failed: DID NOT RAISE <class 'Exception'> test.py:37: Failed __________________________ test_load_from_incomplete ___________________________ def test_load_from_incomplete(): incomplete_content = b'ULBMP\x01\x0c\x00\x02\x00\x02\x00\x00\x00\x00' > with pytest.raises(Exception): E Failed: DID NOT RAISE <class 'Exception'> test.py:128: Failed =========================== short test summary info ============================ FAILED test.py::test_image_init_raises_exception - Failed: DID NOT RAISE <class 'Exception'> FAILED test.py::test_load_from_incomplete - Failed: DID NOT RAISE <class 'Exception'> ========================= 2 failed, 12 passed in 0.11s ========================= batchayw@batchayw-Precision-5520:~/Téléchargements/Yassin/phase1$
Reply
#3
Thos are not "Errors", those are failed tests.

The test complains because this does not raise an exception.
    with pytest.raises(Exception):
        Image(1, 1, [(0, 0, 0)])
(0, 0, 0) is a valid pixel, and [(0, 0, 0)] is sufficient to create a 1 pixel image.

This doesn't raise an exception either.
    incomplete_content = b'ULBMP\x01\x0c\x00\x02\x00\x02\x00\x00\x00\x00'
    with pytest.raises(Exception):
        _bytes_as_img(incomplete_content)
What exception did you expect this to raise?

Now stop triple posting, and next time write a shorter example.
Reply
#4
Quote:Code to write
You are asked to write the following classes:
Pixel in a pixel.py file
Image in an image.py file;
Encoder and Decoder in an encocher.py file.
The Pixel class represents, as its name suggests, a pixel and can contain three integers between 0 and 255: the values for the red, green, and blue channels. This type must be immutable: the RGB values cannot be changed, but the instances themselves can be compared. Two instances of Pixel must be comparable using the operator.
The Image class must contain the following methods:

__init__(self, width: int, height: int, pixels: list[Pixel]), the constructor which takes parameters width and height representing the dimensions of the image, and a list of size width-height of instances of the Pixel class representing the image pixels.
__getitem__(self, pos: tuple[int,int]) -> Pixel, to override the indexing operator [] for reading pixels.
__setitem__(self, pos: tuple[int,int], value: Pixel), to override the assignment operator for writing pixels.
__eq__(self, other: 'Image') -> bool, to override the equality operator.
The special methods __getitem__ and __setitem__ should raise an IndexError exception if pos is not a valid position in the image.
The Encoder class should contain the following methods:
__init__(self, img: Image), the constructor which takes as parameter the image to be encoded.
A method, let's call it encode, which encodes the received image and saves it in ULBMP version 1.0 format in the file whose path is provided as a parameter.
On the other hand, the Decoder class should have a single static method load_from(path: str) -> Image which loads the encoded image file from the specified path and returns it as an Image object. If there is an error in the format of the file, this function should raise an exception.
buran write Feb-20-2024, 08:59 PM:
Please,post in English
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Smile Exception with raise and input artemisellada 3 2,504 Apr-23-2021, 08:19 PM
Last Post: jefsummers
  Raise an exception for syntax error sbabu 8 3,177 Feb-10-2020, 01:57 AM
Last Post: sbabu
  raise error mcgrim 4 2,836 May-09-2019, 08:37 PM
Last Post: mcgrim

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020