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?
CodePudding user response:
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.
CodePudding user response:
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')"