Unit test for decorator in django

Eg:
 
 
@require_http_methods(['POST', 'PUT'])
def set_session_chip(request, chip_id):
    try:
        print "chip_id", chip_id
        chip = Chip.objects.get(id=chip_id)
        set_latest_chip(request, chip_id)
        chip_name = chip.name
        print "chip_name",chip_name
    except Chip.DoesNotExist as e:
        print "haii"        chip_name = None        logger.error("Error message in set_session_chip function: %s" % e)
    return http_response_json({'chip_id': chip_id, 'chip_name': chip_name})
 
 
 
so for  
@require_http_methods(['POST', 'PUT'])..
 
 
how to add unit test case 


class TestSendSetSessionChip(unittest.TestCase):
    def setUp(self):
        # Mock prepare        self.request = Mock()
        self.request.method = 'POST'        self.response = ()

    @patch('ipcat.views.http_response_json')
    @patch('ipcat.views.set_latest_chip')
    @patch('ipcat.views.Chip')
    def test_set_session_chip_valid_chipid(self, chip, set_latest_chip, http_response_json):

        # Mock Prepare        self.chip_id = 79        chip_mock = Mock()
        chip_mock.name = 'QAD682 (Horus)'
        # return value        chip.objects.get.return_value = chip_mock
        set_latest_chip(self.request, self.chip_id)
        http_response_json.return_value = self.response

        # function call        res = set_session_chip(self.request, self.chip_id)

        # assertion        http_response_json.assert_called_with({'chip_id': self.chip_id, 'chip_name': chip_mock.name})
        self.assertEqual(res, self.response)




so it will solve it ..............

No comments:

Post a Comment