我正在关注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文件中的结果时,测试已经可以了网址完全符合我的要求,以下是终端的错误详情
______________________________ test_listings_info _________________________listing_keys = ['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()断言isinstance(响应,字典)断言响应['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”数字存在,但测试无法看到它 . 测试是否正确至关重要,任何人都可以在我的代码中看到错误吗?在开始时,我说我已经按照我的教程进行了操作,这里没有显示代码,但它与教程完全相同,并且所有测试都通过 .
1 回答
测试失败,因为响应JSON中没有
id
键,而不是URL . 您应该始终使用dict.get(key)
从dict中检索值,因为如果key
不在dict中,则使用dict[key]
抛出KeyError .