Jeanne Lane
Jeanne Lane

Reputation: 505

Python assertIn test statement not finding string?

I am using assertIn to test that a part of the result in JSON string is correct.

test_json = some_function_returning_a_dict()
self.assertIn(expected_json, test_json, "did not match expected output")

The error is

AssertionError: "'abc': '1.0012'," not found in [{'abc': '1.0012',...

I used Ctrl + F over the inner string, and it was in the resulting string.
I'm using Python 3.0

Upvotes: 0

Views: 154

Answers (3)

KSab
KSab

Reputation: 592

It looks like you are attempting to find a string inside a dictionary, which will check to see if the string you are giving is a key of the specified dictionary. Firstly don't convert your first dictionary to a string, and secondly do something like all(item in test_json.items() for item in expected_json.items())

Upvotes: 1

Prune
Prune

Reputation: 77880

Right. Python's in operator works on an iterable object. The clause in test_json means, "is the given item a key of the dictionary". It does not search the dictionary for a key:value pair.

To do this, use a two-step process:

assertIn('abc', test_json)
assertEquals('1.0012', test_json['abc'])

Doing this with appropriate variables and references is left as an exercise for the student. :-)

Upvotes: 3

iScrE4m
iScrE4m

Reputation: 882

"'abc': '1.0012'," is a string and {'abc': '1.0012', } is an entry in dictionary

You want to be checking for the dictionary entry in json, not a string

Upvotes: 1

Related Questions