Mock, UnitTest, JSON

He tenido un problema con la creación de una prueba de unidad para asegurarse de que el método que me gustaría funcione bien. Ejecutarlo con pruebas de prueba sin embargo no dio cobertura.

import unittest from mock import Mock, patch, MagicMock from django.conf import settings from hackathon.scripts.steam import * class SteamTests(unittest.TestCase): def setup(self): self.API_URL = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/' self.APIKEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx' self.userID = 'Marorin' self.steamnum = '76561197997115778' def testGetUserIDNum(self): '''Test for steam.py method''' # Pulling from setUp userID = self.userID API_URL = self.API_URL APIKEY = self.APIKEY # constructing the URL self.url = API_URL + '?' + APIKEY + '&' + userID with patch('hackathon.scripts.steam.steamIDpulling') as mock_steamIDPulling: # Mocking the return value of this method. mock_steamIDpulling = 76561197997115778 self.assertEqual(steamIDPulling(userID,APIKEY),mock_steamIDpulling) 

Método para obtener información:

  def steamIDPulling(SteamUN,key): #Pulls out and returns the steam id number for use in steam queries. steaminfo = {'key': key,'vanityurl': SteamUN} a = requests.get('api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/';, params=steaminfo) k = json.loads(a.content) SteamID = k['response']['steamid'] return SteamID 

 # Mocking the return value of this method. mock_steamIDpulling = 76561197997115778 

Debiera ser:

 # Mocking the return value of this method. mock_steamIDpulling.return_value = 76561197997115778 

Sin embargo, su código realmente no tiene sentido. Si está intentando probar el valor de retorno de steamIDpulling , simplemente haga lo siguiente:

 def testGetUserIDNum(self): '''Test for steam.py method''' # Pulling from setUp userID = self.userID API_URL = self.API_URL APIKEY = self.APIKEY # constructing the URL self.url = API_URL + '?' + APIKEY + '&' + userID self.assertEqual(steamIDPulling(userID,APIKEY), 76561197997115778) 

La burla solo es necesaria si es necesario cambiar un valor dentro del método probado (a menos que esté probando la biblioteca mock ). Para burlarse de la biblioteca de solicitud, haga:

 def testGetUserIDNum(self): '''Test for steam.py method''' # Pulling from setUp userID = self.userID API_URL = self.API_URL APIKEY = self.APIKEY # constructing the URL self.url = API_URL + '?' + APIKEY + '&' + userID with patch("requests.get") as mock_requests_get: mock_requests_get.return_value = """{"response": {"streamid":76561197997115778}}""" self.assertEqual(steamIDPulling(userID,APIKEY), 76561197997115778)