I've a method that returns a list of objects that meet certain criteria
result = find_objects(some_criteria)
print("%r" % result)
>> [<my_object.my_object object at 0x开发者_StackOverflow社区85abbcc>]
I would like to write a pytest to verify the operation of find_objects()
def test_finder(testbed):
result = testbed.find_objects(some_criteria)
assert result is [<my_object.my_object object at 0x85abbcc>]
So far, pytest is pointing to the left angle-bracket (<) and declaring "SyntaxError"
I'm thinking that even if I get this to work, it will fail in the future when 'my_object' is stored in another location. If I have multiple instances, how would I confirm that the correct number of them were reported?
In this context, what is the pythonic way to verify the output of a method that returns objects?
js
As you guessed, the problem is trying to do an 'is' comparison. 'is' means 'is the exact same object', and even two objects that appear identical can fail this test.
Here are some things you might want to test
- No exception was raised
The object returned was the right type
assert isinstance(object, ResultClass)
The object returned has some specific attributes
assert result.attribute == attribute
That kind of thing. I don't think there is an 'accepted' way to check, just several things you might want to check and it's up to you to determine what is you want to check. Using 'is' is a bad idea, and comparing to location in memory is a bad idea.
You can try:
assert isinstance(result, my_object.my_object)
You could also try comparing on the string representation (which is essentially what you're doing, except missing the quotes.) isinstance docs Might also want to take a look at the repr docs for an idea of what's happening in your print statement. The angle brackets mean it isn't a plug-in replacement for the object.
The line
assert result is [<my_object.my_object object at 0x85abbcc>]
actually is a syntax error in Python :)
If you want to check the type and length you can do something like:
assert len(result) == 1
for x in result:
assert isinstance(result, my_object.my_object)
精彩评论