我正在遵循有关api here的教程,并且正在遵循确切的代码,我也正在为Etsy应用修改代码,这是我第二次测试的代码,该教程的代码与教程,并且有效。以下代码已经过修改,可以与Etsy APi一起使用。
#etsywrapper/__core.py
from . import session
class Listings(object):
def __init__(self, id):
self.id = id
def info(self):
path = 'https://openapi.etsy.com/v2/listings/{}/inventory'.format(self.id)
response = session.get(path)
return response.json()
@staticmethod
def active():
path = 'https://openapi.etsy.com/v2/shops/:shop_id/listings/active'
response = session.get(path)
return response.json()
和
#etsywrapper/__init__.py
import os
import requests
ETSY_API_KEY = os.environ.get('ETSY_API_KEY', None)
class APIKeyMissingError(Exception):
pass
if ETSY_API_KEY is None:
raise APIKeyMissingError(
"All methods require an API key. See "
"https://developers.themoviedb.org/3/getting-started/introduction "
"for how to retrieve an authentication token from "
"The Movie Database"
)
session = requests.Session()
session.params = {}
session.params['api_key'] = ETSY_API_KEY
from .__core import Listings
和
#tests/test_etsywrapper.py
from pytest import fixture
from etsywrapper import Listings
import vcr
@fixture
def listing_keys():
# Responsible only for returning the test data
return ['listing_id']
@vcr.use_cassette('tests/vcr_cassettes/listing-info.yml')
def test_listings_info(listing_keys):
"""test api call to get listings"""
listings_instance = Listings(648597757)
response = listings_instance.info()
assert isinstance(response, dict)
assert response['id'] == 648597757, "id should be in response"
assert set(listing_keys).issubset(response.keys()), "All keys should be in the response"
@vcr.use_cassette('tests/vcr_cassettes/listings_active.yml')
def test_listings_active():
"""tests shop active listings"""
response = Listings.active()
assert isinstance(response, dict)
assert isinstance(response['results'], list)
assert isinstance(response['results'][0], dict)
assert set(listing_keys()).issubset(response['results'][0].keys())
然后我用“ ETSY_API_KEY ='my_api_code_here'py.test”运行测试 测试结果表明我在第一个测试中有一个错误,但是当我查看vcr文件中的结果时,测试完全符合我的要求,URL正确了,这是来自终端的错误详细信息
______________________________ test_listings_info _________________________listing_keys = ['listing_id'] @ vcr.use_cassette('tests / vcr_cassettes / listing-info.yml') def test_listings_info(listing_keys): “”“测试api调用以获取列表”“” listings_instance =列表(648597757) 响应= listings_instance.info() 断言isinstance(响应,字典) 断言response ['id'] == 648597757,“ id应该在响应中” E KeyError:“ id” tests / test_etsywrapper.py:18:KeyError
这是我期望的网址
https://openapi.etsy.com/v2/listings/648597757/inventory?api_key=“ my_api_key”
,您可以看到测试中期望的“ id”号,但测试无法看到它。测试是否正确至关重要,有人可以看到我的代码中的错误吗?在开始的时候,我说我遵循了教程,这里没有显示该代码,但它与教程相同,并且可以通过所有测试。
答案 0 :(得分:0)
测试失败,因为响应JSON(而不是URL)中没有id
键。您应该始终使用dict.get(key)
从字典中检索值,因为如果dict[key]
不在字典中,则使用key
会引发KeyError。