Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading