简体   繁体   中英

Python how to assert that a method has been called

I have the following test case in python.

class RulesTest(TestCase):

    request_length = 484
    url = "http://www.ndtv.com"

    def setUp(self):
        har_data = open('/Users/rokumar/SiteAnalysisGit/Src/hct/hct/test.har')
        self.data = json.load(har_data)
        self.rule = models.Rule(name=RULES.DNS,user=None,
            threshold=None)
        self.rule.save()

    def tearDown(self):
        self.rule.delete()

    def test_parse_har(self):
        with patch.object(rules, 'add_dns_analysis', return_value=None) as \
           dns_mock: 
            dns_mock.add_dns_analysis('test result', 'test url')
            result = rules.parse_har(self.data,[self.rule],RulesTest.url)
            self.assertEqual(result[RULES.TOTAL_REQUESTS], 484)
            self.assertEqual(result[RULES.HTML_SIZE], 241592)
            self.assertEqual(result[RULES.JS_SIZE], 1006469)
            dns_mock.assert_called_once_with('test result', 'test url')

The last assertion fails telling that the actual call got made. Why is python not bypassing this call.

Maybe you want to check if the method add_dns_analysis was call by parse_har() :

Rewrite your test as

def test_parse_har(self):
    with patch.object(rules, 'add_dns_analysis', return_value=None) as \
       dns_mock: 
        result = rules.parse_har(self.data,[self.rule],RulesTest.url)
        self.assertEqual(result[RULES.TOTAL_REQUESTS], 484)
        self.assertEqual(result[RULES.HTML_SIZE], 241592)
        self.assertEqual(result[RULES.JS_SIZE], 1006469)
        dns_mock.assert_called_once_with('test result', 'test url')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM