0

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

1
  • 1
    A dict is not a JSON string, and testing for the presence of a substring would be a horrible way to validate a JSON string anyway. Commented Sep 7, 2016 at 23:07

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Or you could use the items() view.
Right. I left most of the solution to the "student".
1

"'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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.