Python unittest - asserting dictionary with lists

后端 未结 4 776
挽巷
挽巷 2021-02-19 08:22

While writing some tests for my class, I encountered interesting simple problem. I would like to assertDictEqual two dictionaries containing some list. But this lists may not be

相关标签:
4条回答
  • 2021-02-19 08:28

    maybe you can check for the two elements separately:

        obj_dict = obj.exportToDict()
        self.assertEqual(resulting_dictionary['state'], obj_dict['state'])
        self.assertCountEqual(resulting_dictionary['neighbours'], obj_dict['neighbours'])
    
    0 讨论(0)
  • 2021-02-19 08:35

    You can do:

    a = {i:sorted(j) if isinstance(j, list) else j for i,j in resulting_dictionary.iteritems()}
    b = {i:sorted(j) if isinstance(j, list) else j for i,j in obj.exportToDict().iteritems()}
    self.assertDictEqual(a, b)
    
    0 讨论(0)
  • 2021-02-19 08:46

    How about using all:

    assert all( (k,v) in resulting_dictionary.iteritems() 
                for (k,v) in obj.exportToDict().iteritems() )
    

    I use something like this with py.test, but I think it should work for you.


    A commenter pointed out that the order will screw me here---fair enough...I'd just use sets, then.

    0 讨论(0)
  • 2021-02-19 08:50

    You might try PyHamcrest (Example corrected)

    assert_that(obj.exportToDict(), has_entries(
                                        { 'state': 2347,
                                          'neighbours': contains_inanyorder(1,2,3) }))
    

    (The first value 2347 actually gets wrapped in an implicit equal_to matcher.)

    0 讨论(0)
提交回复
热议问题