pythonarraysdoctest

How do I add bytearrays to doctests?


This is my function signature,

def fun12(bytes_var: bytearray, signed: bool) -> (int):

When I do,

print(fun12(b'\x00\x10',False))

My code works just fine, but when I have something like the following in my doctest comments,

>>> fun12(b'\x00\x10',False)
16

I get an error,

Failed example:
    fun12(b'',False)
Exception raised:
    Traceback (most recent call last):
      File "/Users/usr12/.pyenv/versions/3.10.0/lib/python3.10/doctest.py", line 1348, in __run
        exec(compile(example.source, filename, "single",
    ValueError: source code string cannot contain null bytes
**********************************************************************
1 items had failures:
   1 of   1 in __main__
***Test Failed*** 1 failures.

It seems as though I can't send byte array values to a dockets function, but how else can I specify my test cases?


Solution

  • Keep in mind that the test is being typed as part of a string. Writing something like

    """
    >>> fun12(b'\x00\x10',False)
    16
    """
    

    creates a string that actually contains a null character (and a character with Unicode code point 16), not the Python source code for a bytes literal.

    Therefore, the backslashes need to be escaped:

    """
    >>> fun12(b'\\x00\\x10',False)
    16
    """
    

    This way, the docstring actually contains a backslash, lowercase x, etc., such that when the string is interpreted as Python source code, it creates the desired bytes object.