我遵循的是一个关于api here的教程,我遵循的是确切的代码,我还修改了Etsy应用程序的代码,这是我的第二个测试代码,教程代码与教程完全相同,可以正常工作。下面的代码已经过修改,可以与etsyapi一起使用。你知道吗
#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\u API\u KEY='my\u API\u code\u here'运行测试py.试验" 测试的结果显示我在第一次测试中有一个错误,但是当我查看vcr文件中的结果时,测试结果与我想要的URL完全一致,下面是terminal的错误详细信息
______________________________ 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() assert isinstance(response, dict) assert response['id'] == 648597757, "id should be in response" E KeyError: 'id' tests/test_etsywrapper.py:18: KeyError
这是我想要的网址
https://openapi.etsy.com/v2/listings/648597757/inventory?api_key="my_api_key"
正如您所看到的,测试中预期的“id”号在那里,但是测试看不到它。测试是正确的是至关重要的,有人能看到我代码中的错误吗?最后,我说我已经遵循了教程,虽然这里没有显示代码,但它与教程完全相同,并且所有测试都通过了。你知道吗
测试失败,因为响应JSON中没有
id
键,而URL中没有。您应该始终使用dict.get(key)
从dict中检索值,因为如果key
不在dict中,则使用dict[key]
会抛出KeyError相关问题 更多 >
编程相关推荐