0

我試圖使用Google Api Discovery HttpMockSequence,但我不斷收到以下錯誤:如何嘲笑谷歌API探索HttpResponseSequence

InvalidJsonError: 
-------------------- >> begin captured logging << -------------------- 
googleapiclient.discovery: INFO: URL being requested: GET https://www.googleapis.com/discovery/v1/apis/webmasters/v3/rest 
googleapiclient.discovery: ERROR: Failed to parse as JSON: /home/user/development/projectname/tests/build_response_data.json 
--------------------- >> end captured logging << --------------------- 

這裏是我/試圖做:

tests.py

build_response = self.datafile('build_response_data.json') 
request_data = self.datafile('saved_request_data.json') 

http_auth = HttpMockSequence([ 
    ({'status': '200'}, build_response), 
    ({'status': '200'}, request_data) 
]) 

service = build('webmasters', 
       'v3', 
       http=http_auth, 
       developerKey='myapikey1234') 

,你可以在這裏看到我的JSON文件: build_response_data.json

問題發生在文件中googleapiclient/discovery.py

我只是不能似乎明白了這是怎麼回事on..can誰能告訴我就行了功能_retrieve_discovery_doc 253我究竟做錯了什麼?

回答

2

要anwser我自己的問題,並幫助其他人在同一條船上,問題是,_retrieve_discovery_doc試圖將funtion以內容爲JSON加載按該行253:

service = json.loads(content) 

,但因爲我是不打開文件並閱讀它的內容,json實際上是試圖加載url爲json。

所以對於第一部分的解決辦法是改變HttpMockSequence到:

http_auth = HttpMockSequence([ 
    ({'status': '200'}, open(build_response, 'rb').read()), 
    ({'status': '200'}, open(request_data, 'rb').read()) 
]) 

然後從request_data文件你做返回的數據:

site_url = 'www.example.com' 
body = { 
    'startDate': '2015-09-11', 
    'endDate': '2015-12-12', 
    'dimensions': ['date'] 
} 
build_response_data = self.datafile('build_response_data.json') 
request_data = self.datafile('saved_request_data.json') 
http_auth = HttpMockSequence([ 
    ({'status': '200'}, open(build_response_data, 'rb').read()), 
    ({'status': '200'}, open(request_data, 'rb').read()) 
]) 

service = build('webmasters', 
       'v3', 
       http=http_auth, 
       developerKey='myapikey1234') 
service.searchanalytics().query(siteUrl=site_url, body=body).execute() 

希望這會幫助別人。