How do I add bytearrays to doctests?

Question:

This is my function signature,

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

When I do,

print(fun12(b'x00x10',False))

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

>>> fun12(b'x00x10',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?

Asked By: RandomDude8470

||

Answers:

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

"""
>>> fun12(b'x00x10',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.

Answered By: Karl Knechtel

Another way to prevent escaping characters is to make the string raw:

This will create a null byte which is invalid inside byte strings (it needs to be escaped)

def a():
   """
   print(b'x00')
   """

print(a.__doc__)
# prints "print(b'�')" where � is a null byte

This will create a string containing x00 which is valid python code:

def b():
   r"""
   print(b'x00')
   """ #notice the r before the """

print(b.__doc__)
# prints "print(b'x00')"
Answered By: mousetail
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.