Answer the question
In order to leave comments, you need to log in
How does unittest work?
program code
import requests
class Asteroid():
BASE_API_URL = 'http://www.neowsapp.com/rest/v1/neo/{}?api_key=DEMO_KEY'
def __init__(self,spk_id):
self.api_url = self.BASE_API_URL.format(spk_id)
def get_data(self):
return requests.get(self.api_url).json()
@property
def name(self):
return self.get_data()['name']
@property
def diameter(self):
return float(self.get_data()['estimated_diameter']['meters']['estimated\
_diameter_max'])
import json
import unittest
from unittest.mock import patch
from asteroid import Asteroid
class TestAsteroid(unittest.TestCase):
def setUp(self):
self.asteroid = Asteroid(3726710)
#в случае, если интернета нет, возвращаются данные из текстового файла, с тем же содержимым, которое возвращает API
def mocked_get_data(self):
with open('asteroid_info.txt', 'r') as f:
return json.loads(f.read())
@patch('asteroid.Asteroid.get_data' , mocked_get_data)
def test_name(self):
self.assertEqual(
self.asteroid.name, '(2015 RC)')
@patch('asteroid.Asteroid.get_data' , mocked_get_data)
def test_diameter(self):
self.assertEqual(self.asteroid.diameter, 82.0427064882)
if __name__ == '__main__':
unittest.main()
@patch('asteroid.Asteroid.get_data' , mocked_get_data)
def mocked_get_data(self):
with open('asteroid_info.txt', 'r') as f:
data = json.loads(f.read())
# неявно self.asteroid.name = data['name']
a = Asteroid(32241432)
Answer the question
In order to leave comments, you need to log in
@patch('asteroid.Asteroid.get_data' , mocked_get_data)
Why
a = Asteroid(32241432)
Runs quietly
def __init__(self,spk_id):
self.api_url = self.BASE_API_URL.format(spk_id)
and here a.name output the list from ConnectionError ,
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question