Nuke it from orbit, it's the only way to be sure

This commit is contained in:
Steven Bazyl committed 2015-04-16 17:21:38 -07:00
1 parent 82f69445ad
commit 9b7809174d
72 files changed
-11948

No files matched your search

-8
View File
@@ -1,8 +0,0 @@
{ "access_token":"access_token_123456789",
"authorization_uri":"https://accounts.google.com/o/oauth2/auth",
"client_id":"123456789p.apps.googleusercontent.com",
"client_secret":"very_secret",
"expires_in":3600,
"refresh_token":"refresh_token_12345679",
"token_credential_uri":"https://accounts.google.com/o/oauth2/token",
"issued_at":1386053761}
-1
View File
@@ -1 +0,0 @@
{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"i8YaXdGgiQ4_KrTVNGsB7QP1","token_uri":"https://accounts.google.com/o/oauth2/token","client_email":"","client_x509_cert_url":"","client_id":"898243283568.apps.googleusercontent.com","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs"}}
Binary file not shown.
-33
View File
@@ -1,33 +0,0 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus posuere urna bibendum diam vulputate fringilla. Fusce elementum fermentum justo id aliquam. Integer vel felis ut arcu elementum lacinia. Duis congue urna eget nisl dapibus tristique molestie turpis sollicitudin. Vivamus in justo quam. Proin condimentum mollis tortor at molestie. Cras luctus, nunc a convallis iaculis, est risus consequat nisi, sit amet sollicitudin metus mi a urna. Aliquam accumsan, massa quis condimentum varius, sapien massa faucibus nibh, a dignissim magna nibh a lacus. Nunc aliquet, nunc ac pulvinar consectetur, sapien lacus hendrerit enim, nec dapibus lorem mi eget risus. Praesent vitae justo eget dolor blandit ullamcorper. Duis id nibh vitae sem aliquam vehicula et ac massa. In neque elit, molestie pulvinar viverra at, vestibulum quis velit.
Mauris sit amet placerat enim. Duis vel tellus ac dui auctor tincidunt id nec augue. Donec ut blandit turpis. Mauris dictum urna id urna vestibulum accumsan. Maecenas sagittis urna vitae erat facilisis gravida. Phasellus tellus augue, commodo ut iaculis vitae, interdum ut dolor. Proin at dictum lorem. Quisque pellentesque neque ante, vitae rutrum elit. Pellentesque sit amet erat orci. Praesent justo diam, tristique eu tempus ut, vestibulum eget dui. Maecenas et elementum justo. Cras a augue a elit porttitor placerat eget ut magna.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam adipiscing tellus in arcu bibendum volutpat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed laoreet faucibus tristique. Duis metus eros, molestie eget dignissim in, imperdiet fermentum nulla. Vestibulum laoreet lorem eu justo vestibulum lobortis. Praesent pharetra leo vel mauris rhoncus commodo sollicitudin ante auctor. Ut sagittis, tortor nec placerat rutrum, neque ipsum cursus nisl, ut lacinia magna risus ac risus. Sed volutpat commodo orci, sodales fermentum dui accumsan eu. Donec egestas ullamcorper elit at condimentum. In euismod sodales posuere. Nullam lacinia tempus molestie. Etiam vitae ullamcorper dui. Fusce congue suscipit arcu, at consectetur diam gravida id. Quisque augue urna, commodo eleifend volutpat vitae, tincidunt ac ligula. Curabitur eget orci nisl, vel placerat ipsum.
Curabitur rutrum euismod nisi, consectetur varius tortor condimentum non. Pellentesque rhoncus nisi eu purus ultricies suscipit. Morbi ante nisi, varius nec molestie bibendum, pharetra quis enim. Proin eget nunc ante. Cras aliquam enim vel nunc laoreet ut facilisis nunc interdum. Fusce libero ipsum, posuere eget blandit quis, bibendum vitae quam. Integer dictum faucibus lacus eget facilisis. Duis adipiscing tortor magna, vel tincidunt risus. In non augue eu nisl sodales cursus vel eget nisi. Maecenas dignissim lectus elementum eros fermentum gravida et eget leo. Aenean quis cursus arcu. Mauris posuere purus non diam mattis vehicula. Integer nec orci velit.
Integer ac justo ac magna adipiscing condimentum vitae tincidunt dui. Morbi augue arcu, blandit nec interdum sit amet, condimentum vel nisl. Nulla vehicula tincidunt laoreet. Aliquam ornare elementum urna, sed vehicula magna porta id. Vestibulum dictum ultrices tortor sit amet tincidunt. Praesent bibendum, metus vel volutpat interdum, nisl nunc cursus libero, vel congue ligula mi et felis. Nulla mollis elementum nulla, in accumsan risus consequat at. Suspendisse potenti. Vestibulum enim lorem, dignissim ut porta vestibulum, porta eget mi. Fusce a elit ac dui sodales gravida. Pellentesque sed elit at dui dapibus mattis a non arcu.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In nec posuere augue. Praesent non suscipit arcu. Sed nibh risus, lacinia ut molestie vitae, tristique eget turpis. Sed pretium volutpat arcu, non rutrum leo volutpat sed. Maecenas quis neque nisl, sit amet ornare dolor. Nulla pharetra pulvinar tellus sed eleifend. Aliquam eget mattis nulla. Nulla dictum vehicula velit, non facilisis lorem volutpat id. Fusce scelerisque sem vitae purus dapibus lobortis. Mauris ac turpis nec nibh consequat porttitor. Ut sit amet iaculis lorem. Vivamus blandit erat ac odio venenatis fringilla a sit amet ante. Quisque ut urna sed augue laoreet sagittis.
Integer nisl urna, bibendum id lobortis in, tempor non velit. Fusce sed volutpat quam. Suspendisse eu placerat purus. Maecenas quis feugiat lectus. Sed accumsan malesuada dui, a pretium purus facilisis quis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc ac purus id lacus malesuada placerat et in nunc. Ut imperdiet tincidunt est, at consectetur augue egestas hendrerit. Pellentesque eu erat a dui dignissim adipiscing. Integer quis leo non felis placerat eleifend. Fusce luctus mi a lorem mattis eget accumsan libero posuere. Sed pellentesque, odio id pharetra tempus, enim quam placerat metus, auctor aliquam elit mi facilisis quam. Nam at velit et eros rhoncus accumsan.
Donec tellus diam, fringilla ac viverra fringilla, rhoncus sit amet purus. Cras et ligula sed nibh tempor gravida. Aliquam id tempus mauris. Ut convallis quam sed arcu varius eget mattis magna tincidunt. Aliquam et suscipit est. Sed metus augue, tristique sed accumsan eget, euismod et augue. Nam augue sapien, placerat vel facilisis eu, tempor id risus. Aliquam mollis egestas mi. Fusce scelerisque convallis mauris quis blandit. Mauris nec ante id lacus sagittis tincidunt ornare vehicula dui. Curabitur tristique mattis nunc, vel cursus libero viverra feugiat. Suspendisse at sapien velit, a lacinia dolor. Vivamus in est non odio feugiat lacinia sodales ut magna.
Donec interdum ligula id ipsum dapibus consectetur. Pellentesque vitae posuere ligula. Morbi rhoncus bibendum eleifend. Suspendisse fringilla nunc at elit malesuada vitae ullamcorper lorem laoreet. Suspendisse a ante at ipsum iaculis cursus. Duis accumsan ligula quis nibh luctus pretium. Duis ultrices scelerisque dolor, et vulputate lectus commodo ut.
Vestibulum ac tincidunt lorem. Vestibulum lorem massa, dictum a scelerisque ut, convallis vitae eros. Morbi ipsum nisl, lacinia non tempor nec, lobortis id diam. Fusce quis magna nunc. Proin ultricies congue justo sed mattis. Vestibulum sit amet arcu tellus. Quisque ultricies porta massa iaculis vehicula. Vestibulum sollicitudin tempor urna vel sodales. Pellentesque ultricies tellus vel metus porta nec iaculis sapien mollis. Maecenas ullamcorper, metus eget imperdiet sagittis, odio orci dapibus neque, in vulputate nunc nibh non libero. Donec velit quam, lobortis quis tempus a, hendrerit id arcu.
Donec nec ante at tortor dignissim mattis. Curabitur vehicula tincidunt magna id sagittis. Proin euismod dignissim porta. Curabitur non turpis purus, in rutrum nulla. Nam turpis nulla, tincidunt et hendrerit non, posuere nec enim. Curabitur leo enim, lobortis ut placerat id, condimentum nec massa. In bibendum, lectus sit amet molestie commodo, felis massa rutrum nisl, ac fermentum ligula lacus in ipsum.
Pellentesque mi nulla, scelerisque vitae tempus id, consequat a augue. Quisque vel nisi sit amet ipsum faucibus laoreet sed vitae lorem. Praesent nunc tortor, volutpat ac commodo non, pharetra sed neque. Curabitur nec felis at mi blandit aliquet eu ornare justo. Mauris dignissim purus quis nisl porttitor interdum. Aenean id ipsum enim, blandit commodo justo. Quisque facilisis elit quis velit commodo scelerisque lobortis sapien condimentum. Cras sit amet porttitor velit. Praesent nec tempor arcu.
Donec varius mi adipiscing elit semper vel feugiat ipsum dictum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec non quam nisl, ac mattis justo. Vestibulum sed massa eget velit tristique auctor ut ac sapien. Curabitur aliquet ligula eget dui ornare at scelerisque mauris faucibus. Vestibulum id mauris metus, sed vestibulum nibh. Nulla egestas dictum blandit. Mauris vitae nibh at dui mollis lobortis. Phasellus sem leo, euismod at fringilla quis, mollis in nibh. Aenean vel lacus et elit pharetra elementum. Aliquam at ligula id sem bibendum volutpat. Pellentesque quis elit a massa dapibus viverra ut et lorem. Donec nulla eros, iaculis nec commodo vel, suscipit sit amet tortor. Integer tempor, elit at viverra imperdiet, velit sapien laoreet nunc, id laoreet ligula risus vel risus. Nullam sed tortor metus.
In nunc orci, tempor vulputate pretium vel, suscipit quis risus. Suspendisse accumsan facilisis felis eget posuere. Donec a faucibus felis. Proin nibh erat, sollicitudin quis vestibulum id, tincidunt quis justo. In sed purus eu nisi dignissim condimentum. Sed mattis dapibus lorem id vulputate. Suspendisse nec elit a augue interdum consequat quis id magna. In eleifend aliquam tempor. In in lacus augue.
Ut euismod sollicitudin lorem, id aliquam magna dictum sed. Nunc fringilla lobortis nisi sed consectetur. Nulla facilisi. Aenean nec lobortis augue. Curabitur ullamcorper dapibus libero, vel pellentesque arcu sollicitudin non. Praesent varius, turpis nec sollicitudin bibendum, elit tortor rhoncus lacus, gravida luctus leo nisi in felis. Ut metus eros, molestie non faucibus vel, condimentum ac elit.
Suspendisse nisl justo, lacinia sit amet interdum nec, tincidunt placerat urna. Suspendisse potenti. In et odio sed purus malesuada cursus sed nec lectus. Cras commodo, orci sit amet hendrerit iaculis, nunc urna facilisis tellus, vel laoreet odio nulla quis nibh. Maecenas ut justo ut lacus posuere sodales. Vestibulum facilisis fringilla diam at volutpat. Proin a hendrerit urna. Aenean placerat pulvinar arcu, sit amet lobortis neque eleifend in. Aenean risus nulla, facilisis ut tincidunt vitae, fringilla at ligula. Praesent eleifend est at sem lacinia auctor. Nulla ornare nunc in erat laoreet blandit.
Suspendisse pharetra leo ac est porta consequat. Nunc sem nibh, gravida vel aliquam a, ornare in tortor. Nulla vel sapien et felis placerat pellentesque id scelerisque nisl. Praesent et posuere.
-19
View File
@@ -1,19 +0,0 @@
Bag Attributes
friendlyName: privatekey
localKeyID: 54 69 6D 65 20 31 33 35 31 38 38 38 31 37 38 36 39 36
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDYDyPb3GhyFx5i/wxS/jFsO6wSLys1ehAk6QZoBXGlg7ETVrIJ
HYh9gXQUno4tJiQoaO8wOvleIRrqI0LkiftCXKWVSrzOiV+O9GkKx1byw1yAIZus
QdwMT7X0O9hrZLZwhICWC9s6cGhnlCVxLIP/+JkVK7hxEq/LxoSszNV77wIDAQAB
AoGAa2G69L7quil7VMBmI6lqbtyJfNAsrXtpIq8eG/z4qsZ076ObAKTI/XeldcoH
57CZL+xXVKU64umZMt0rleJuGXdlauEUbsSx+biGewRfGTgC4rUSjmE539rBvmRW
gaKliorepPMp/+B9CcG/2YfDPRvG/2cgTXJHVvneo+xHL4ECQQD2Jx5Mvs8z7s2E
jY1mkpRKqh4Z7rlitkAwe1NXcVC8hz5ASu7ORyTl8EPpKAfRMYl1ofK/ozT1URXf
kL5nChPfAkEA4LPUJ6cqrY4xrrtdGaM4iGIxzen5aZlKz/YNlq5LuQKbnLLHMuXU
ohp/ynpqNWbcAFbmtGSMayxGKW5+fJgZ8QJAUBOZv82zCmn9YcnK3juBEmkVMcp/
dKVlbGAyVJgAc9RrY+78kQ6D6mmnLgpfwKYk2ae9mKo3aDbgrsIfrtWQcQJAfFGi
CEpJp3orbLQG319ZsMM7MOTJdC42oPZOMFbAWFzkAX88DKHx0bn9h+XQizkccSej
Ppz+v3DgZJ3YZ1Cz0QJBALiqIokZ+oa3AY6oT0aiec6txrGvNPPbwOsrBpFqGNbu
AByzWWBoBi40eKMSIR30LqN9H8YnJ91Aoy1njGYyQaw=
-----END RSA PRIVATE KEY-----
-584
View File
@@ -1,584 +0,0 @@
{
"kind": "discovery#describeItem",
"name": "zoo",
"version": "v1",
"description": "Zoo API used for testing",
"basePath": "/zoo/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "zoo/v1/",
"rpcPath": "/rpc",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"features": [
"dataWrapper"
],
"schemas": {
"Animal": {
"id": "Animal",
"type": "object",
"properties": {
"etag": {
"type": "string"
},
"kind": {
"type": "string",
"default": "zoo#animal"
},
"name": {
"type": "string"
},
"photo": {
"type": "object",
"properties": {
"filename": {
"type": "string"
},
"hash": {
"type": "string"
},
"hashAlgorithm": {
"type": "string"
},
"size": {
"type": "integer"
},
"type": {
"type": "string"
}
}
}
}
},
"Animal2": {
"id": "Animal2",
"type": "object",
"properties": {
"kind": {
"type": "string",
"default": "zoo#animal"
},
"name": {
"type": "string"
}
}
},
"AnimalFeed": {
"id": "AnimalFeed",
"type": "object",
"properties": {
"etag": {
"type": "string"
},
"items": {
"type": "array",
"items": {
"$ref": "Animal"
}
},
"kind": {
"type": "string",
"default": "zoo#animalFeed"
}
}
},
"AnimalMap": {
"id": "AnimalMap",
"type": "object",
"properties": {
"etag": {
"type": "string"
},
"animals": {
"type": "object",
"description": "Map of animal id to animal data",
"additionalProperties": {
"$ref": "Animal"
}
},
"kind": {
"type": "string",
"default": "zoo#animalMap"
}
}
},
"LoadFeed": {
"id": "LoadFeed",
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"doubleVal": {
"type": "number"
},
"nullVal": {
"type": "null"
},
"booleanVal": {
"type": "boolean",
"description": "True or False."
},
"anyVal": {
"type": "any",
"description": "Anything will do."
},
"enumVal": {
"type": "string"
},
"kind": {
"type": "string",
"default": "zoo#loadValue"
},
"longVal": {
"type": "integer"
},
"stringVal": {
"type": "string"
}
}
}
},
"kind": {
"type": "string",
"default": "zoo#loadFeed"
}
}
}
},
"methods": {
"query": {
"path": "query",
"id": "bigquery.query",
"httpMethod": "GET",
"parameters": {
"q": {
"type": "string",
"location": "query",
"required": false,
"repeated": false
},
"i": {
"type": "integer",
"location": "query",
"required": false,
"repeated": false,
"minimum": "0",
"maximum": "4294967295",
"default": "20"
},
"n": {
"type": "number",
"location": "query",
"required": false,
"repeated": false
},
"b": {
"type": "boolean",
"location": "query",
"required": false,
"repeated": false
},
"a": {
"type": "any",
"location": "query",
"required": false,
"repeated": false
},
"o": {
"type": "object",
"location": "query",
"required": false,
"repeated": false
},
"e": {
"type": "string",
"location": "query",
"required": false,
"repeated": false,
"enum": [
"foo",
"bar"
]
},
"er": {
"type": "string",
"location": "query",
"required": false,
"repeated": true,
"enum": [
"one",
"two",
"three"
]
},
"rr": {
"type": "string",
"location": "query",
"required": false,
"repeated": true,
"pattern": "[a-z]+"
}
}
}
},
"resources": {
"my": {
"resources": {
"favorites": {
"methods": {
"list": {
"path": "favorites/@me/mine",
"id": "zoo.animals.mine",
"httpMethod": "GET",
"parameters": {
"max-results": {
"location": "query",
"required": false
}
}
}
}
}
}
},
"global": {
"resources": {
"print": {
"methods": {
"assert": {
"path": "global/print/assert",
"id": "zoo.animals.mine",
"httpMethod": "GET",
"parameters": {
"max-results": {
"location": "query",
"required": false
}
}
}
}
}
}
},
"animals": {
"methods": {
"crossbreed": {
"path": "animals/crossbreed",
"id": "zoo.animals.crossbreed",
"httpMethod": "POST",
"description": "Cross-breed animals",
"response": {
"$ref": "Animal2"
},
"mediaUpload": {
"accept": [
"image/png"
],
"protocols": {
"simple": {
"multipart": true,
"path": "upload/activities/{userId}/@self"
},
"resumable": {
"multipart": true,
"path": "upload/activities/{userId}/@self"
}
}
}
},
"delete": {
"path": "animals/{name}",
"id": "zoo.animals.delete",
"httpMethod": "DELETE",
"description": "Delete animals",
"parameters": {
"name": {
"location": "path",
"required": true,
"description": "Name of the animal to delete",
"type": "string"
}
},
"parameterOrder": [
"name"
]
},
"get": {
"path": "animals/{name}",
"id": "zoo.animals.get",
"httpMethod": "GET",
"description": "Get animals",
"supportsMediaDownload": true,
"parameters": {
"name": {
"location": "path",
"required": true,
"description": "Name of the animal to load",
"type": "string"
},
"projection": {
"location": "query",
"type": "string",
"enum": [
"full"
],
"enumDescriptions": [
"Include everything"
]
}
},
"parameterOrder": [
"name"
],
"response": {
"$ref": "Animal"
}
},
"getmedia": {
"path": "animals/{name}",
"id": "zoo.animals.get",
"httpMethod": "GET",
"description": "Get animals",
"parameters": {
"name": {
"location": "path",
"required": true,
"description": "Name of the animal to load",
"type": "string"
},
"projection": {
"location": "query",
"type": "string",
"enum": [
"full"
],
"enumDescriptions": [
"Include everything"
]
}
},
"parameterOrder": [
"name"
]
},
"insert": {
"path": "animals",
"id": "zoo.animals.insert",
"httpMethod": "POST",
"description": "Insert animals",
"request": {
"$ref": "Animal"
},
"response": {
"$ref": "Animal"
},
"mediaUpload": {
"accept": [
"image/png"
],
"maxSize": "1KB",
"protocols": {
"simple": {
"multipart": true,
"path": "upload/activities/{userId}/@self"
},
"resumable": {
"multipart": true,
"path": "upload/activities/{userId}/@self"
}
}
}
},
"list": {
"path": "animals",
"id": "zoo.animals.list",
"httpMethod": "GET",
"description": "List animals",
"parameters": {
"max-results": {
"location": "query",
"description": "Maximum number of results to return",
"type": "integer",
"minimum": "0"
},
"name": {
"location": "query",
"description": "Restrict result to animals with this name",
"type": "string"
},
"projection": {
"location": "query",
"type": "string",
"enum": [
"full"
],
"enumDescriptions": [
"Include absolutely everything"
]
},
"start-token": {
"location": "query",
"description": "Pagination token",
"type": "string"
}
},
"response": {
"$ref": "AnimalFeed"
}
},
"patch": {
"path": "animals/{name}",
"id": "zoo.animals.patch",
"httpMethod": "PATCH",
"description": "Update animals",
"parameters": {
"name": {
"location": "path",
"required": true,
"description": "Name of the animal to update",
"type": "string"
}
},
"parameterOrder": [
"name"
],
"request": {
"$ref": "Animal"
},
"response": {
"$ref": "Animal"
}
},
"update": {
"path": "animals/{name}",
"id": "zoo.animals.update",
"httpMethod": "PUT",
"description": "Update animals",
"parameters": {
"name": {
"location": "path",
"description": "Name of the animal to update",
"type": "string"
}
},
"parameterOrder": [
"name"
],
"request": {
"$ref": "Animal"
},
"response": {
"$ref": "Animal"
}
}
}
},
"load": {
"methods": {
"list": {
"path": "load",
"id": "zoo.load.list",
"httpMethod": "GET",
"response": {
"$ref": "LoadFeed"
}
}
}
},
"loadNoTemplate": {
"methods": {
"list": {
"path": "loadNoTemplate",
"id": "zoo.loadNoTemplate.list",
"httpMethod": "GET"
}
}
},
"scopedAnimals": {
"methods": {
"list": {
"path": "scopedanimals",
"id": "zoo.scopedAnimals.list",
"httpMethod": "GET",
"description": "List animals (scoped)",
"parameters": {
"max-results": {
"location": "query",
"description": "Maximum number of results to return",
"type": "integer",
"minimum": "0"
},
"name": {
"location": "query",
"description": "Restrict result to animals with this name",
"type": "string"
},
"projection": {
"location": "query",
"type": "string",
"enum": [
"full"
],
"enumDescriptions": [
"Include absolutely everything"
]
},
"start-token": {
"location": "query",
"description": "Pagination token",
"type": "string"
}
},
"response": {
"$ref": "AnimalFeed"
}
}
}
}
}
}
-122
View File
@@ -1,122 +0,0 @@
require 'spec_helper'
require 'google/api_client'
require 'google/api_client/version'
describe Google::APIClient::Storage do
let(:client) { Google::APIClient.new(:application_name => 'API Client Tests') }
let(:root_path) { File.expand_path(File.join(__FILE__, '..', '..', '..')) }
let(:json_file) { File.expand_path(File.join(root_path, 'fixtures', 'files', 'auth_stored_credentials.json')) }
let(:store) { double }
let(:client_stub) { double }
subject { Google::APIClient::Storage.new(store) }
describe 'authorize' do
it 'should authorize' do
expect(subject).to respond_to(:authorization)
expect(subject.store).to be == store
end
end
describe 'authorize' do
describe 'with credentials' do
it 'should initialize a new OAuth Client' do
expect(subject).to receive(:load_credentials).and_return({:first => 'a dummy'})
expect(client_stub).to receive(:issued_at=)
expect(client_stub).to receive(:expired?).and_return(false)
expect(Signet::OAuth2::Client).to receive(:new).and_return(client_stub)
expect(subject).not_to receive(:refresh_authorization)
subject.authorize
end
it 'should refresh authorization' do
expect(subject).to receive(:load_credentials).and_return({:first => 'a dummy'})
expect(client_stub).to receive(:issued_at=)
expect(client_stub).to receive(:expired?).and_return(true)
expect(Signet::OAuth2::Client).to receive(:new).and_return(client_stub)
expect(subject).to receive(:refresh_authorization)
auth = subject.authorize
expect(auth).to be == subject.authorization
expect(auth).not_to be_nil
end
end
describe 'without credentials' do
it 'should return nil' do
expect(subject.authorization).to be_nil
expect(subject).to receive(:load_credentials).and_return({})
expect(subject.authorize).to be_nil
expect(subject.authorization).to be_nil
end
end
end
describe 'write_credentials' do
it 'should call store to write credentials' do
authorization_stub = double
expect(authorization_stub).to receive(:refresh_token).and_return(true)
expect(subject).to receive(:credentials_hash)
expect(subject.store).to receive(:write_credentials)
subject.write_credentials(authorization_stub)
expect(subject.authorization).to be == authorization_stub
end
it 'should not call store to write credentials' do
expect(subject).not_to receive(:credentials_hash)
expect(subject.store).not_to receive(:write_credentials)
expect {
subject.write_credentials()
}.not_to raise_error
end
it 'should not call store to write credentials' do
expect(subject).not_to receive(:credentials_hash)
expect(subject.store).not_to receive(:write_credentials)
expect {
subject.write_credentials('something')
}.not_to raise_error
end
end
describe 'refresh_authorization' do
it 'should call refresh and write credentials' do
expect(subject).to receive(:write_credentials)
authorization_stub = double
expect(subject).to receive(:authorization).and_return(authorization_stub)
expect(authorization_stub).to receive(:refresh!).and_return(true)
subject.refresh_authorization
end
end
describe 'load_credentials' do
it 'should call store to load credentials' do
expect(subject.store).to receive(:load_credentials)
subject.send(:load_credentials)
end
end
describe 'credentials_hash' do
it 'should return an hash' do
authorization_stub = double
expect(authorization_stub).to receive(:access_token)
expect(authorization_stub).to receive(:client_id)
expect(authorization_stub).to receive(:client_secret)
expect(authorization_stub).to receive(:expires_in)
expect(authorization_stub).to receive(:refresh_token)
expect(authorization_stub).to receive(:issued_at).and_return('100')
allow(subject).to receive(:authorization).and_return(authorization_stub)
credentials = subject.send(:credentials_hash)
expect(credentials).to include(:access_token)
expect(credentials).to include(:authorization_uri)
expect(credentials).to include(:client_id)
expect(credentials).to include(:client_secret)
expect(credentials).to include(:expires_in)
expect(credentials).to include(:refresh_token)
expect(credentials).to include(:token_credential_uri)
expect(credentials).to include(:issued_at)
end
end
end
@@ -1,40 +0,0 @@
require 'spec_helper'
require 'google/api_client'
require 'google/api_client/version'
describe Google::APIClient::FileStore do
let(:root_path) { File.expand_path(File.join(__FILE__, '..','..','..', '..','..')) }
let(:json_file) { File.expand_path(File.join(root_path, 'fixtures', 'files', 'auth_stored_credentials.json')) }
let(:credentials_hash) {{
"access_token"=>"my_access_token",
"authorization_uri"=>"https://accounts.google.com/o/oauth2/auth",
"client_id"=>"123456_test_client_id@.apps.googleusercontent.com",
"client_secret"=>"123456_client_secret",
"expires_in"=>3600,
"refresh_token"=>"my_refresh_token",
"token_credential_uri"=>"https://accounts.google.com/o/oauth2/token",
"issued_at"=>1384440275
}}
subject{Google::APIClient::FileStore.new('a file path')}
it 'should have a path' do
expect(subject.path).to be == 'a file path'
subject.path = 'an other file path'
expect(subject.path).to be == 'an other file path'
end
it 'should load credentials' do
subject.path = json_file
credentials = subject.load_credentials
expect(credentials).to include('access_token', 'authorization_uri', 'refresh_token')
end
it 'should write credentials' do
io_stub = StringIO.new
expect(subject).to receive(:open).and_return(io_stub)
subject.write_credentials(credentials_hash)
end
end
@@ -1,70 +0,0 @@
require 'spec_helper'
require 'google/api_client'
require 'google/api_client/version'
describe Google::APIClient::RedisStore do
let(:root_path) { File.expand_path(File.join(__FILE__, '..', '..', '..', '..', '..')) }
let(:json_file) { File.expand_path(File.join(root_path, 'fixtures', 'files', 'auth_stored_credentials.json')) }
let(:redis) {double}
let(:credentials_hash) { {
"access_token" => "my_access_token",
"authorization_uri" => "https://accounts.google.com/o/oauth2/auth",
"client_id" => "123456_test_client_id@.apps.googleusercontent.com",
"client_secret" => "123456_client_secret",
"expires_in" => 3600,
"refresh_token" => "my_refresh_token",
"token_credential_uri" => "https://accounts.google.com/o/oauth2/token",
"issued_at" => 1384440275
} }
subject { Google::APIClient::RedisStore.new('a redis instance') }
it 'should have a redis instance' do
expect(subject.redis).to be == 'a redis instance'
subject.redis = 'an other redis instance'
expect(subject.redis).to be == 'an other redis instance'
end
describe 'load_credentials' do
it 'should load credentials' do
subject.redis= redis
expect(redis).to receive(:get).and_return(credentials_hash.to_json)
expect(subject.load_credentials).to be == credentials_hash
end
it 'should return nil' do
subject.redis= redis
expect(redis).to receive(:get).and_return(nil)
expect(subject.load_credentials).to be_nil
end
end
describe 'redis_credentials_key' do
context 'without given key' do
it 'should return default key' do
expect(subject.redis_credentials_key).to be == "google_api_credentials"
end
end
context 'with given key' do
let(:redis_store) { Google::APIClient::RedisStore.new('a redis instance', 'another_google_api_credentials') }
it 'should use given key' do
expect(redis_store.redis_credentials_key).to be == "another_google_api_credentials"
end
end
end
describe 'write credentials' do
it 'should write credentials' do
subject.redis= redis
expect(redis).to receive(:set).and_return('ok')
expect(subject.write_credentials(credentials_hash)).to be_truthy
end
end
end
-248
View File
@@ -1,248 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
RSpec.describe Google::APIClient::BatchRequest do
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
after do
# Reset client to not-quite-pristine state
CLIENT.key = nil
CLIENT.user_ip = nil
end
it 'should raise an error if making an empty batch request' do
batch = Google::APIClient::BatchRequest.new
expect(lambda do
CLIENT.execute(batch)
end).to raise_error(Google::APIClient::BatchError)
end
it 'should allow query parameters in batch requests' do
batch = Google::APIClient::BatchRequest.new
batch.add(:uri => 'https://example.com', :parameters => {
'a' => '12345'
})
method, uri, headers, body = batch.to_http_request
expect(body.read).to include("/?a=12345")
end
describe 'with the discovery API' do
before do
CLIENT.authorization = nil
@discovery = CLIENT.discovered_api('discovery', 'v1')
end
describe 'with two valid requests' do
before do
@call1 = {
:api_method => @discovery.apis.get_rest,
:parameters => {
'api' => 'plus',
'version' => 'v1'
}
}
@call2 = {
:api_method => @discovery.apis.get_rest,
:parameters => {
'api' => 'discovery',
'version' => 'v1'
}
}
end
it 'should execute both when using a global callback' do
block_called = 0
ids = ['first_call', 'second_call']
expected_ids = ids.clone
batch = Google::APIClient::BatchRequest.new do |result|
block_called += 1
expect(result.status).to eq(200)
expect(expected_ids).to include(result.response.call_id)
expected_ids.delete(result.response.call_id)
end
batch.add(@call1, ids[0])
batch.add(@call2, ids[1])
CLIENT.execute(batch)
expect(block_called).to eq(2)
end
it 'should execute both when using individual callbacks' do
batch = Google::APIClient::BatchRequest.new
call1_returned, call2_returned = false, false
batch.add(@call1) do |result|
call1_returned = true
expect(result.status).to eq(200)
end
batch.add(@call2) do |result|
call2_returned = true
expect(result.status).to eq(200)
end
CLIENT.execute(batch)
expect(call1_returned).to be_truthy
expect(call2_returned).to be_truthy
end
it 'should raise an error if using the same call ID more than once' do
batch = Google::APIClient::BatchRequest.new
expect(lambda do
batch.add(@call1, 'my_id')
batch.add(@call2, 'my_id')
end).to raise_error(Google::APIClient::BatchError)
end
end
describe 'with a valid request and an invalid one' do
before do
@call1 = {
:api_method => @discovery.apis.get_rest,
:parameters => {
'api' => 'plus',
'version' => 'v1'
}
}
@call2 = {
:api_method => @discovery.apis.get_rest,
:parameters => {
'api' => 0,
'version' => 1
}
}
end
it 'should execute both when using a global callback' do
block_called = 0
ids = ['first_call', 'second_call']
expected_ids = ids.clone
batch = Google::APIClient::BatchRequest.new do |result|
block_called += 1
expect(expected_ids).to include(result.response.call_id)
expected_ids.delete(result.response.call_id)
if result.response.call_id == ids[0]
expect(result.status).to eq(200)
else
expect(result.status).to be >= 400
expect(result.status).to be < 500
end
end
batch.add(@call1, ids[0])
batch.add(@call2, ids[1])
CLIENT.execute(batch)
expect(block_called).to eq(2)
end
it 'should execute both when using individual callbacks' do
batch = Google::APIClient::BatchRequest.new
call1_returned, call2_returned = false, false
batch.add(@call1) do |result|
call1_returned = true
expect(result.status).to eq(200)
end
batch.add(@call2) do |result|
call2_returned = true
expect(result.status).to be >= 400
expect(result.status).to be < 500
end
CLIENT.execute(batch)
expect(call1_returned).to be_truthy
expect(call2_returned).to be_truthy
end
end
end
describe 'with the calendar API' do
before do
CLIENT.authorization = nil
@calendar = CLIENT.discovered_api('calendar', 'v3')
end
describe 'with two valid requests' do
before do
event1 = {
'summary' => 'Appointment 1',
'location' => 'Somewhere',
'start' => {
'dateTime' => '2011-01-01T10:00:00.000-07:00'
},
'end' => {
'dateTime' => '2011-01-01T10:25:00.000-07:00'
},
'attendees' => [
{
'email' => 'myemail@mydomain.tld'
}
]
}
event2 = {
'summary' => 'Appointment 2',
'location' => 'Somewhere as well',
'start' => {
'dateTime' => '2011-01-02T10:00:00.000-07:00'
},
'end' => {
'dateTime' => '2011-01-02T10:25:00.000-07:00'
},
'attendees' => [
{
'email' => 'myemail@mydomain.tld'
}
]
}
@call1 = {
:api_method => @calendar.events.insert,
:parameters => {'calendarId' => 'myemail@mydomain.tld'},
:body => MultiJson.dump(event1),
:headers => {'Content-Type' => 'application/json'}
}
@call2 = {
:api_method => @calendar.events.insert,
:parameters => {'calendarId' => 'myemail@mydomain.tld'},
:body => MultiJson.dump(event2),
:headers => {'Content-Type' => 'application/json'}
}
end
it 'should convert to a correct HTTP request' do
batch = Google::APIClient::BatchRequest.new { |result| }
batch.add(@call1, '1').add(@call2, '2')
request = batch.to_env(CLIENT.connection)
boundary = Google::APIClient::BatchRequest::BATCH_BOUNDARY
expect(request[:method].to_s.downcase).to eq('post')
expect(request[:url].to_s).to eq('https://www.googleapis.com/batch')
expect(request[:request_headers]['Content-Type']).to eq("multipart/mixed;boundary=#{boundary}")
body = request[:body].read
expect(body).to include(@call1[:body])
expect(body).to include(@call2[:body])
end
end
end
end
@@ -1,53 +0,0 @@
# encoding:utf-8
# Copyright 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client/client_secrets'
FIXTURES_PATH = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient::ClientSecrets do
context 'with JSON file' do
let(:file) { File.join(FIXTURES_PATH, 'files', 'client_secrets.json') }
subject(:secrets) { Google::APIClient::ClientSecrets.load(file)}
it 'should load the correct client ID' do
expect(secrets.client_id).to be == '898243283568.apps.googleusercontent.com'
end
it 'should load the correct client secret' do
expect(secrets.client_secret).to be == 'i8YaXdGgiQ4_KrTVNGsB7QP1'
end
context 'serialzed to hash' do
subject(:hash) { secrets.to_hash }
it 'should contain the flow as the first key' do
expect(hash).to have_key "installed"
end
it 'should contain the client ID' do
expect(hash["installed"]["client_id"]).to be == '898243283568.apps.googleusercontent.com'
end
it 'should contain the client secret' do
expect(hash["installed"]["client_secret"]).to be == 'i8YaXdGgiQ4_KrTVNGsB7QP1'
end
end
end
end
-708
View File
@@ -1,708 +0,0 @@
# encoding:utf-8
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'faraday'
require 'multi_json'
require 'compat/multi_json'
require 'signet/oauth_1/client'
require 'google/api_client'
fixtures_path = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient do
include ConnectionHelpers
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
after do
# Reset client to not-quite-pristine state
CLIENT.key = nil
CLIENT.user_ip = nil
end
it 'should raise a type error for bogus authorization' do
expect(lambda do
Google::APIClient.new(:application_name => 'API Client Tests', :authorization => 42)
end).to raise_error(TypeError)
end
it 'should not be able to retrieve the discovery document for a bogus API' do
expect(lambda do
CLIENT.discovery_document('bogus')
end).to raise_error(Google::APIClient::TransmissionError)
expect(lambda do
CLIENT.discovered_api('bogus')
end).to raise_error(Google::APIClient::TransmissionError)
end
it 'should raise an error for bogus services' do
expect(lambda do
CLIENT.discovered_api(42)
end).to raise_error(TypeError)
end
it 'should raise an error for bogus services' do
expect(lambda do
CLIENT.preferred_version(42)
end).to raise_error(TypeError)
end
it 'should raise an error for bogus methods' do
expect(lambda do
CLIENT.execute(42)
end).to raise_error(TypeError)
end
it 'should not return a preferred version for bogus service names' do
expect(CLIENT.preferred_version('bogus')).to eq(nil)
end
describe 'with zoo API' do
it 'should return API instance registered from file' do
zoo_json = File.join(fixtures_path, 'files', 'zoo.json')
contents = File.open(zoo_json, 'rb') { |io| io.read }
api = CLIENT.register_discovery_document('zoo', 'v1', contents)
expect(api).to be_kind_of(Google::APIClient::API)
end
end
describe 'with the prediction API' do
before do
CLIENT.authorization = nil
# The prediction API no longer exposes a v1, so we have to be
# careful about looking up the wrong API version.
@prediction = CLIENT.discovered_api('prediction', 'v1.2')
end
it 'should correctly determine the discovery URI' do
expect(CLIENT.discovery_uri('prediction')).to be ===
'https://www.googleapis.com/discovery/v1/apis/prediction/v1/rest'
end
it 'should correctly determine the discovery URI if :user_ip is set' do
CLIENT.user_ip = '127.0.0.1'
conn = stub_connection do |stub|
stub.get('/discovery/v1/apis/prediction/v1.2/rest?userIp=127.0.0.1') do |env|
[200, {}, '{}']
end
end
CLIENT.execute(
:http_method => 'GET',
:uri => CLIENT.discovery_uri('prediction', 'v1.2'),
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should correctly determine the discovery URI if :key is set' do
CLIENT.key = 'qwerty'
conn = stub_connection do |stub|
stub.get('/discovery/v1/apis/prediction/v1.2/rest?key=qwerty') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:http_method => 'GET',
:uri => CLIENT.discovery_uri('prediction', 'v1.2'),
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should correctly determine the discovery URI if both are set' do
CLIENT.key = 'qwerty'
CLIENT.user_ip = '127.0.0.1'
conn = stub_connection do |stub|
stub.get('/discovery/v1/apis/prediction/v1.2/rest?key=qwerty&userIp=127.0.0.1') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:http_method => 'GET',
:uri => CLIENT.discovery_uri('prediction', 'v1.2'),
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should correctly generate API objects' do
expect(CLIENT.discovered_api('prediction', 'v1.2').name).to eq('prediction')
expect(CLIENT.discovered_api('prediction', 'v1.2').version).to eq('v1.2')
expect(CLIENT.discovered_api(:prediction, 'v1.2').name).to eq('prediction')
expect(CLIENT.discovered_api(:prediction, 'v1.2').version).to eq('v1.2')
end
it 'should discover methods' do
expect(CLIENT.discovered_method(
'prediction.training.insert', 'prediction', 'v1.2'
).name).to eq('insert')
expect(CLIENT.discovered_method(
:'prediction.training.insert', :prediction, 'v1.2'
).name).to eq('insert')
expect(CLIENT.discovered_method(
'prediction.training.delete', 'prediction', 'v1.2'
).name).to eq('delete')
end
it 'should define the origin API in discovered methods' do
expect(CLIENT.discovered_method(
'prediction.training.insert', 'prediction', 'v1.2'
).api.name).to eq('prediction')
end
it 'should not find methods that are not in the discovery document' do
expect(CLIENT.discovered_method(
'prediction.bogus', 'prediction', 'v1.2'
)).to eq(nil)
end
it 'should raise an error for bogus methods' do
expect(lambda do
CLIENT.discovered_method(42, 'prediction', 'v1.2')
end).to raise_error(TypeError)
end
it 'should raise an error for bogus methods' do
expect(lambda do
CLIENT.execute(:api_method => CLIENT.discovered_api('prediction', 'v1.2'))
end).to raise_error(TypeError)
end
it 'should correctly determine the preferred version' do
expect(CLIENT.preferred_version('prediction').version).not_to eq('v1')
expect(CLIENT.preferred_version(:prediction).version).not_to eq('v1')
end
it 'should return a batch path' do
expect(CLIENT.discovered_api('prediction', 'v1.2').batch_path).not_to be_nil
end
it 'should generate valid requests' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
expect(env[:body]).to eq('')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should generate valid requests when parameter value includes semicolon' do
conn = stub_connection do |stub|
# semicolon (;) in parameter value was being converted to
# bare ampersand (&) in 0.4.7. ensure that it gets converted
# to a CGI-escaped semicolon (%3B) instead.
stub.post('/prediction/v1.2/training?data=12345%3B67890') do |env|
expect(env[:body]).to eq('')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345;67890'},
:connection => conn
)
conn.verify
end
it 'should generate valid requests when multivalued parameters are passed' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=1&data=2') do |env|
expect(env.params['data']).to include('1', '2')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => ['1', '2']},
:connection => conn
)
conn.verify
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should allow modification to the base URIs for testing purposes' do
# Using a new client instance here to avoid caching rebased discovery doc
prediction_rebase =
Google::APIClient.new(:application_name => 'API Client Tests').discovered_api('prediction', 'v1.2')
prediction_rebase.method_base =
'https://testing-domain.example.com/prediction/v1.2/'
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training') do |env|
expect(env[:url].host).to eq('testing-domain.example.com')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => prediction_rebase.training.insert,
:parameters => {'data' => '123'},
:connection => conn
)
conn.verify
end
it 'should generate OAuth 1 requests' do
CLIENT.authorization = :oauth_1
CLIENT.authorization.token_credential_key = '12345'
CLIENT.authorization.token_credential_secret = '12345'
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
expect(env[:request_headers]).to have_key('Authorization')
expect(env[:request_headers]['Authorization']).to match(/^OAuth/)
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should generate OAuth 2 requests' do
CLIENT.authorization = :oauth_2
CLIENT.authorization.access_token = '12345'
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
expect(env[:request_headers]).to have_key('Authorization')
expect(env[:request_headers]['Authorization']).to match(/^Bearer/)
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should not be able to execute improperly authorized requests' do
CLIENT.authorization = :oauth_1
CLIENT.authorization.token_credential_key = '12345'
CLIENT.authorization.token_credential_secret = '12345'
result = CLIENT.execute(
@prediction.training.insert,
{'data' => '12345'}
)
expect(result.response.status).to eq(401)
end
it 'should not be able to execute improperly authorized requests' do
CLIENT.authorization = :oauth_2
CLIENT.authorization.access_token = '12345'
result = CLIENT.execute(
@prediction.training.insert,
{'data' => '12345'}
)
expect(result.response.status).to eq(401)
end
it 'should not be able to execute improperly authorized requests' do
expect(lambda do
CLIENT.authorization = :oauth_1
CLIENT.authorization.token_credential_key = '12345'
CLIENT.authorization.token_credential_secret = '12345'
result = CLIENT.execute!(
@prediction.training.insert,
{'data' => '12345'}
)
end).to raise_error(Google::APIClient::ClientError)
end
it 'should not be able to execute improperly authorized requests' do
expect(lambda do
CLIENT.authorization = :oauth_2
CLIENT.authorization.access_token = '12345'
result = CLIENT.execute!(
@prediction.training.insert,
{'data' => '12345'}
)
end).to raise_error(Google::APIClient::ClientError)
end
it 'should correctly handle unnamed parameters' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training') do |env|
expect(env[:request_headers]).to have_key('Content-Type')
expect(env[:request_headers]['Content-Type']).to eq('application/json')
[200, {}, '{}']
end
end
CLIENT.authorization = :oauth_2
CLIENT.authorization.access_token = '12345'
CLIENT.execute(
:api_method => @prediction.training.insert,
:body => MultiJson.dump({"id" => "bucket/object"}),
:headers => {'Content-Type' => 'application/json'},
:connection => conn
)
conn.verify
end
end
describe 'with the plus API' do
before do
CLIENT.authorization = nil
@plus = CLIENT.discovered_api('plus')
end
it 'should correctly determine the discovery URI' do
expect(CLIENT.discovery_uri('plus')).to be ===
'https://www.googleapis.com/discovery/v1/apis/plus/v1/rest'
end
it 'should find APIs that are in the discovery document' do
expect(CLIENT.discovered_api('plus').name).to eq('plus')
expect(CLIENT.discovered_api('plus').version).to eq('v1')
expect(CLIENT.discovered_api(:plus).name).to eq('plus')
expect(CLIENT.discovered_api(:plus).version).to eq('v1')
end
it 'should find methods that are in the discovery document' do
# TODO(bobaman) Fix this when the RPC names are correct
expect(CLIENT.discovered_method(
'plus.activities.list', 'plus'
).name).to eq('list')
end
it 'should define the origin API in discovered methods' do
expect(CLIENT.discovered_method(
'plus.activities.list', 'plus'
).api.name).to eq('plus')
end
it 'should not find methods that are not in the discovery document' do
expect(CLIENT.discovered_method('plus.bogus', 'plus')).to eq(nil)
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.get('/plus/v1/people/107807692475771887386/activities/public') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @plus.activities.list,
:parameters => {
'userId' => '107807692475771887386', 'collection' => 'public'
},
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should correctly validate parameters' do
expect(lambda do
CLIENT.execute(
:api_method => @plus.activities.list,
:parameters => {'alt' => 'json'},
:authenticated => false
)
end).to raise_error(ArgumentError)
end
it 'should correctly validate parameters' do
expect(lambda do
CLIENT.execute(
:api_method => @plus.activities.list,
:parameters => {
'userId' => '107807692475771887386', 'collection' => 'bogus'
},
:authenticated => false
).to_env(CLIENT.connection)
end).to raise_error(ArgumentError)
end
it 'should correctly determine the service root_uri' do
expect(@plus.root_uri.to_s).to eq('https://www.googleapis.com/')
end
end
describe 'with the adsense API' do
before do
CLIENT.authorization = nil
@adsense = CLIENT.discovered_api('adsense', 'v1.3')
end
it 'should correctly determine the discovery URI' do
expect(CLIENT.discovery_uri('adsense', 'v1.3').to_s).to be ===
'https://www.googleapis.com/discovery/v1/apis/adsense/v1.3/rest'
end
it 'should find APIs that are in the discovery document' do
expect(CLIENT.discovered_api('adsense', 'v1.3').name).to eq('adsense')
expect(CLIENT.discovered_api('adsense', 'v1.3').version).to eq('v1.3')
end
it 'should return a batch path' do
expect(CLIENT.discovered_api('adsense', 'v1.3').batch_path).not_to be_nil
end
it 'should find methods that are in the discovery document' do
expect(CLIENT.discovered_method(
'adsense.reports.generate', 'adsense', 'v1.3'
).name).to eq('generate')
end
it 'should not find methods that are not in the discovery document' do
expect(CLIENT.discovered_method('adsense.bogus', 'adsense', 'v1.3')).to eq(nil)
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/adclients') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @adsense.adclients.list,
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should not be able to execute requests without authorization' do
result = CLIENT.execute(
:api_method => @adsense.adclients.list,
:authenticated => false
)
expect(result.response.status).to eq(401)
end
it 'should fail when validating missing required parameters' do
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:authenticated => false
)
end).to raise_error(ArgumentError)
end
it 'should succeed when validating parameters in a correct call' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/reports?dimension=DATE&endDate=2010-01-01&metric=PAGE_VIEWS&startDate=2000-01-01') do |env|
[200, {}, '{}']
end
end
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => 'DATE',
'metric' => 'PAGE_VIEWS'
},
:authenticated => false,
:connection => conn
)
end).not_to raise_error
conn.verify
end
it 'should fail when validating parameters with invalid values' do
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => 'BAD_CHARACTERS=-&*(£&',
'metric' => 'PAGE_VIEWS'
},
:authenticated => false
)
end).to raise_error(ArgumentError)
end
it 'should succeed when validating repeated parameters in a correct call' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/reports?dimension=DATE&dimension=PRODUCT_CODE'+
'&endDate=2010-01-01&metric=CLICKS&metric=PAGE_VIEWS&'+
'startDate=2000-01-01') do |env|
[200, {}, '{}']
end
end
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => ['DATE', 'PRODUCT_CODE'],
'metric' => ['PAGE_VIEWS', 'CLICKS']
},
:authenticated => false,
:connection => conn
)
end).not_to raise_error
conn.verify
end
it 'should fail when validating incorrect repeated parameters' do
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => ['DATE', 'BAD_CHARACTERS=-&*(£&'],
'metric' => ['PAGE_VIEWS', 'CLICKS']
},
:authenticated => false
)
end).to raise_error(ArgumentError)
end
it 'should generate valid requests when multivalued parameters are passed' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/reports?dimension=DATE&dimension=PRODUCT_CODE'+
'&endDate=2010-01-01&metric=CLICKS&metric=PAGE_VIEWS&'+
'startDate=2000-01-01') do |env|
expect(env.params['dimension']).to include('DATE', 'PRODUCT_CODE')
expect(env.params['metric']).to include('CLICKS', 'PAGE_VIEWS')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => ['DATE', 'PRODUCT_CODE'],
'metric' => ['PAGE_VIEWS', 'CLICKS']
},
:authenticated => false,
:connection => conn
)
conn.verify
end
end
describe 'with the Drive API' do
before do
CLIENT.authorization = nil
@drive = CLIENT.discovered_api('drive', 'v1')
end
it 'should include media upload info methods' do
expect(@drive.files.insert.media_upload).not_to eq(nil)
end
it 'should include accepted media types' do
expect(@drive.files.insert.media_upload.accepted_types).not_to be_empty
end
it 'should have an upload path' do
expect(@drive.files.insert.media_upload.uri_template).not_to eq(nil)
end
it 'should have a max file size' do
expect(@drive.files.insert.media_upload.max_size).not_to eq(nil)
end
end
describe 'with the Pub/Sub API' do
before do
CLIENT.authorization = nil
@pubsub = CLIENT.discovered_api('pubsub', 'v1beta2')
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.get('/v1beta2/projects/12345/topics') do |env|
expect(env[:url].host).to eq('pubsub.googleapis.com')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @pubsub.projects.topics.list,
:parameters => {'project' => 'projects/12345'},
:connection => conn
)
conn.verify
end
it 'should correctly determine the service root_uri' do
expect(@pubsub.root_uri.to_s).to eq('https://pubsub.googleapis.com/')
end
it 'should discover correct method URIs' do
list = CLIENT.discovered_method(
"pubsub.projects.topics.list", "pubsub", "v1beta2"
)
expect(list.uri_template.pattern).to eq(
"https://pubsub.googleapis.com/v1beta2/{+project}/topics"
)
publish = CLIENT.discovered_method(
"pubsub.projects.topics.publish", "pubsub", "v1beta2"
)
expect(publish.uri_template.pattern).to eq(
"https://pubsub.googleapis.com/v1beta2/{+topic}:publish"
)
end
end
end
-98
View File
@@ -1,98 +0,0 @@
# Encoding: utf-8
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
RSpec.describe Google::APIClient::Gzip do
def create_connection(&block)
Faraday.new do |b|
b.response :charset
b.response :gzip
b.adapter :test do |stub|
stub.get '/', &block
end
end
end
it 'should ignore non-zipped content' do
conn = create_connection do |env|
[200, {}, 'Hello world']
end
result = conn.get('/')
expect(result.body).to eq("Hello world")
end
it 'should decompress gziped content' do
conn = create_connection do |env|
[200, { 'Content-Encoding' => 'gzip'}, Base64.decode64('H4sICLVGwlEAA3RtcADzSM3JyVcozy/KSeECANXgObcMAAAA')]
end
result = conn.get('/')
expect(result.body).to eq("Hello world\n")
end
it 'should inflate with the correct charset encoding' do
conn = create_connection do |env|
[200,
{ 'Content-Encoding' => 'deflate', 'Content-Type' => 'application/json;charset=BIG5'},
Base64.decode64('eJxb8nLp7t2VAA8fBCI=')]
end
result = conn.get('/')
expect(result.body.encoding).to eq(Encoding::BIG5)
expect(result.body).to eq('日本語'.encode("BIG5"))
end
describe 'with API Client' do
before do
@client = Google::APIClient.new(:application_name => 'test')
@client.authorization = nil
end
it 'should send gzip in user agent' do
conn = create_connection do |env|
agent = env[:request_headers]['User-Agent']
expect(agent).not_to be_nil
expect(agent).to include 'gzip'
[200, {}, 'Hello world']
end
@client.execute(:uri => 'http://www.example.com/', :connection => conn)
end
it 'should send gzip in accept-encoding' do
conn = create_connection do |env|
encoding = env[:request_headers]['Accept-Encoding']
expect(encoding).not_to be_nil
expect(encoding).to include 'gzip'
[200, {}, 'Hello world']
end
@client.execute(:uri => 'http://www.example.com/', :connection => conn)
end
it 'should not send gzip in accept-encoding if disabled for request' do
conn = create_connection do |env|
encoding = env[:request_headers]['Accept-Encoding']
expect(encoding).not_to include('gzip') unless encoding.nil?
[200, {}, 'Hello world']
end
response = @client.execute(:uri => 'http://www.example.com/', :gzip => false, :connection => conn)
puts response.status
end
end
end
-178
View File
@@ -1,178 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
fixtures_path = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient::UploadIO do
it 'should reject invalid file paths' do
expect(lambda do
media = Google::APIClient::UploadIO.new('doesnotexist', 'text/plain')
end).to raise_error
end
describe 'with a file' do
before do
@file = File.expand_path('files/sample.txt', fixtures_path)
@media = Google::APIClient::UploadIO.new(@file, 'text/plain')
end
it 'should report the correct file length' do
expect(@media.length).to eq(File.size(@file))
end
it 'should have a mime type' do
expect(@media.content_type).to eq('text/plain')
end
end
describe 'with StringIO' do
before do
@content = "hello world"
@media = Google::APIClient::UploadIO.new(StringIO.new(@content), 'text/plain', 'test.txt')
end
it 'should report the correct file length' do
expect(@media.length).to eq(@content.length)
end
it 'should have a mime type' do
expect(@media.content_type).to eq('text/plain')
end
end
end
RSpec.describe Google::APIClient::RangedIO do
before do
@source = StringIO.new("1234567890abcdef")
@io = Google::APIClient::RangedIO.new(@source, 1, 5)
end
it 'should return the correct range when read entirely' do
expect(@io.read).to eq("23456")
end
it 'should maintain position' do
expect(@io.read(1)).to eq('2')
expect(@io.read(2)).to eq('34')
expect(@io.read(2)).to eq('56')
end
it 'should allow rewinds' do
expect(@io.read(2)).to eq('23')
@io.rewind()
expect(@io.read(2)).to eq('23')
end
it 'should allow setting position' do
@io.pos = 3
expect(@io.read).to eq('56')
end
it 'should not allow position to be set beyond range' do
@io.pos = 10
expect(@io.read).to eq('')
end
it 'should return empty string when read amount is zero' do
expect(@io.read(0)).to eq('')
end
it 'should return empty string at EOF if amount is nil' do
@io.read
expect(@io.read).to eq('')
end
it 'should return nil at EOF if amount is positive int' do
@io.read
expect(@io.read(1)).to eq(nil)
end
end
RSpec.describe Google::APIClient::ResumableUpload do
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
after do
# Reset client to not-quite-pristine state
CLIENT.key = nil
CLIENT.user_ip = nil
end
before do
@drive = CLIENT.discovered_api('drive', 'v1')
@file = File.expand_path('files/sample.txt', fixtures_path)
@media = Google::APIClient::UploadIO.new(@file, 'text/plain')
@uploader = Google::APIClient::ResumableUpload.new(
:media => @media,
:api_method => @drive.files.insert,
:uri => 'https://www.googleapis.com/upload/drive/v1/files/12345')
end
it 'should consider 20x status as complete' do
request = @uploader.to_http_request
@uploader.process_http_response(mock_result(200))
expect(@uploader.complete?).to eq(true)
end
it 'should consider 30x status as incomplete' do
request = @uploader.to_http_request
@uploader.process_http_response(mock_result(308))
expect(@uploader.complete?).to eq(false)
expect(@uploader.expired?).to eq(false)
end
it 'should consider 40x status as fatal' do
request = @uploader.to_http_request
@uploader.process_http_response(mock_result(404))
expect(@uploader.expired?).to eq(true)
end
it 'should detect changes to location' do
request = @uploader.to_http_request
@uploader.process_http_response(mock_result(308, 'location' => 'https://www.googleapis.com/upload/drive/v1/files/abcdef'))
expect(@uploader.uri.to_s).to eq('https://www.googleapis.com/upload/drive/v1/files/abcdef')
end
it 'should resume from the saved range reported by the server' do
@uploader.chunk_size = 200
@uploader.to_http_request # Send bytes 0-199, only 0-99 saved
@uploader.process_http_response(mock_result(308, 'range' => '0-99'))
method, url, headers, body = @uploader.to_http_request # Send bytes 100-299
expect(headers['Content-Range']).to eq("bytes 100-299/#{@media.length}")
expect(headers['Content-length']).to eq("200")
end
it 'should resync the offset after 5xx errors' do
@uploader.chunk_size = 200
@uploader.to_http_request
@uploader.process_http_response(mock_result(500)) # Invalidates range
method, url, headers, body = @uploader.to_http_request # Resync
expect(headers['Content-Range']).to eq("bytes */#{@media.length}")
expect(headers['Content-length']).to eq("0")
@uploader.process_http_response(mock_result(308, 'range' => '0-99'))
method, url, headers, body = @uploader.to_http_request # Send next chunk at correct range
expect(headers['Content-Range']).to eq("bytes 100-299/#{@media.length}")
expect(headers['Content-length']).to eq("200")
end
def mock_result(status, headers = {})
reference = Google::APIClient::Reference.new(:api_method => @drive.files.insert)
double('result', :status => status, :headers => headers, :reference => reference)
end
end
-29
View File
@@ -1,29 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
RSpec.describe Google::APIClient::Request do
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
it 'should normalize parameter names to strings' do
request = Google::APIClient::Request.new(:uri => 'https://www.google.com', :parameters => {
:a => '1', 'b' => '2'
})
expect(request.parameters['a']).to eq('1')
expect(request.parameters['b']).to eq('2')
end
end
-207
View File
@@ -1,207 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
RSpec.describe Google::APIClient::Result do
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
describe 'with the plus API' do
before do
CLIENT.authorization = nil
@plus = CLIENT.discovered_api('plus', 'v1')
@reference = Google::APIClient::Reference.new({
:api_method => @plus.activities.list,
:parameters => {
'userId' => 'me',
'collection' => 'public',
'maxResults' => 20
}
})
@request = @reference.to_http_request
# Response double
@response = double("response")
allow(@response).to receive(:status).and_return(200)
allow(@response).to receive(:headers).and_return({
'etag' => '12345',
'x-google-apiary-auth-scopes' =>
'https://www.googleapis.com/auth/plus.me',
'content-type' => 'application/json; charset=UTF-8',
'date' => 'Mon, 23 Apr 2012 00:00:00 GMT',
'cache-control' => 'private, max-age=0, must-revalidate, no-transform',
'server' => 'GSE',
'connection' => 'close'
})
end
describe 'with a next page token' do
before do
allow(@response).to receive(:body).and_return(
<<-END_OF_STRING
{
"kind": "plus#activityFeed",
"etag": "FOO",
"nextPageToken": "NEXT+PAGE+TOKEN",
"selfLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?",
"nextLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?maxResults=20&pageToken=NEXT%2BPAGE%2BTOKEN",
"title": "Plus Public Activity Feed for ",
"updated": "2012-04-23T00:00:00.000Z",
"id": "123456790",
"items": []
}
END_OF_STRING
)
@result = Google::APIClient::Result.new(@reference, @response)
end
it 'should indicate a successful response' do
expect(@result.error?).to be_falsey
end
it 'should return the correct next page token' do
expect(@result.next_page_token).to eq('NEXT+PAGE+TOKEN')
end
it 'should escape the next page token when calling next_page' do
reference = @result.next_page
expect(Hash[reference.parameters]).to include('pageToken')
expect(Hash[reference.parameters]['pageToken']).to eq('NEXT+PAGE+TOKEN')
url = reference.to_env(CLIENT.connection)[:url]
expect(url.to_s).to include('pageToken=NEXT%2BPAGE%2BTOKEN')
end
it 'should return content type correctly' do
expect(@result.media_type).to eq('application/json')
end
it 'should return the result data correctly' do
expect(@result.data?).to be_truthy
expect(@result.data.class.to_s).to eq(
'Google::APIClient::Schema::Plus::V1::ActivityFeed'
)
expect(@result.data.kind).to eq('plus#activityFeed')
expect(@result.data.etag).to eq('FOO')
expect(@result.data.nextPageToken).to eq('NEXT+PAGE+TOKEN')
expect(@result.data.selfLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?'
)
expect(@result.data.nextLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?' +
'maxResults=20&pageToken=NEXT%2BPAGE%2BTOKEN'
)
expect(@result.data.title).to eq('Plus Public Activity Feed for ')
expect(@result.data.id).to eq("123456790")
expect(@result.data.items).to be_empty
end
end
describe 'without a next page token' do
before do
allow(@response).to receive(:body).and_return(
<<-END_OF_STRING
{
"kind": "plus#activityFeed",
"etag": "FOO",
"selfLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?",
"title": "Plus Public Activity Feed for ",
"updated": "2012-04-23T00:00:00.000Z",
"id": "123456790",
"items": []
}
END_OF_STRING
)
@result = Google::APIClient::Result.new(@reference, @response)
end
it 'should not return a next page token' do
expect(@result.next_page_token).to eq(nil)
end
it 'should return content type correctly' do
expect(@result.media_type).to eq('application/json')
end
it 'should return the result data correctly' do
expect(@result.data?).to be_truthy
expect(@result.data.class.to_s).to eq(
'Google::APIClient::Schema::Plus::V1::ActivityFeed'
)
expect(@result.data.kind).to eq('plus#activityFeed')
expect(@result.data.etag).to eq('FOO')
expect(@result.data.selfLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?'
)
expect(@result.data.title).to eq('Plus Public Activity Feed for ')
expect(@result.data.id).to eq("123456790")
expect(@result.data.items).to be_empty
end
end
describe 'with JSON error response' do
before do
allow(@response).to receive(:body).and_return(
<<-END_OF_STRING
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
END_OF_STRING
)
allow(@response).to receive(:status).and_return(400)
@result = Google::APIClient::Result.new(@reference, @response)
end
it 'should return error status correctly' do
expect(@result.error?).to be_truthy
end
it 'should return the correct error message' do
expect(@result.error_message).to eq('Parse Error')
end
end
describe 'with 204 No Content response' do
before do
allow(@response).to receive(:body).and_return('')
allow(@response).to receive(:status).and_return(204)
allow(@response).to receive(:headers).and_return({})
@result = Google::APIClient::Result.new(@reference, @response)
end
it 'should indicate no data is available' do
expect(@result.data?).to be_falsey
end
it 'should return nil for data' do
expect(@result.data).to eq(nil)
end
it 'should return nil for media_type' do
expect(@result.media_type).to eq(nil)
end
end
end
end
@@ -1,169 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
fixtures_path = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient::KeyUtils do
it 'should read PKCS12 files from the filesystem' do
if RUBY_PLATFORM == 'java' && RUBY_VERSION.start_with?('1.8')
pending "Reading from PKCS12 not supported on jruby 1.8.x"
end
path = File.expand_path('files/privatekey.p12', fixtures_path)
key = Google::APIClient::KeyUtils.load_from_pkcs12(path, 'notasecret')
expect(key).not_to eq(nil)
end
it 'should read PKCS12 files from loaded files' do
if RUBY_PLATFORM == 'java' && RUBY_VERSION.start_with?('1.8')
pending "Reading from PKCS12 not supported on jruby 1.8.x"
end
path = File.expand_path('files/privatekey.p12', fixtures_path)
content = File.read(path)
key = Google::APIClient::KeyUtils.load_from_pkcs12(content, 'notasecret')
expect(key).not_to eq(nil)
end
it 'should read PEM files from the filesystem' do
path = File.expand_path('files/secret.pem', fixtures_path)
key = Google::APIClient::KeyUtils.load_from_pem(path, 'notasecret')
expect(key).not_to eq(nil)
end
it 'should read PEM files from loaded files' do
path = File.expand_path('files/secret.pem', fixtures_path)
content = File.read(path)
key = Google::APIClient::KeyUtils.load_from_pem(content, 'notasecret')
expect(key).not_to eq(nil)
end
end
RSpec.describe Google::APIClient::JWTAsserter do
include ConnectionHelpers
before do
@key = OpenSSL::PKey::RSA.new 2048
end
it 'should generate valid JWTs' do
asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key)
jwt = asserter.to_authorization.to_jwt
expect(jwt).not_to eq(nil)
claim = JWT.decode(jwt, @key.public_key, true)
claim = claim[0] if claim[0]
expect(claim["iss"]).to eq('client1')
expect(claim["scope"]).to eq('scope1 scope2')
end
it 'should allow impersonation' do
conn = stub_connection do |stub|
stub.post('/o/oauth2/token') do |env|
params = Addressable::URI.form_unencode(env[:body])
JWT.decode(params.assoc("assertion").last, @key.public_key)
expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer'])
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/abcdef1234567890",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
end
asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key)
auth = asserter.authorize('user1@email.com', { :connection => conn })
expect(auth).not_to eq(nil?)
expect(auth.person).to eq('user1@email.com')
conn.verify
end
it 'should send valid access token request' do
conn = stub_connection do |stub|
stub.post('/o/oauth2/token') do |env|
params = Addressable::URI.form_unencode(env[:body])
JWT.decode(params.assoc("assertion").last, @key.public_key)
expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer'])
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/abcdef1234567890",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
end
asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key)
auth = asserter.authorize(nil, { :connection => conn })
expect(auth).not_to eq(nil?)
expect(auth.access_token).to eq("1/abcdef1234567890")
conn.verify
end
it 'should be refreshable' do
conn = stub_connection do |stub|
stub.post('/o/oauth2/token') do |env|
params = Addressable::URI.form_unencode(env[:body])
JWT.decode(params.assoc("assertion").last, @key.public_key)
expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer'])
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/abcdef1234567890",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
stub.post('/o/oauth2/token') do |env|
params = Addressable::URI.form_unencode(env[:body])
JWT.decode(params.assoc("assertion").last, @key.public_key)
expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer'])
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/0987654321fedcba",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
end
asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key)
auth = asserter.authorize(nil, { :connection => conn })
expect(auth).not_to eq(nil?)
expect(auth.access_token).to eq("1/abcdef1234567890")
auth.fetch_access_token!(:connection => conn)
expect(auth.access_token).to eq("1/0987654321fedcba")
conn.verify
end
end
RSpec.describe Google::APIClient::ComputeServiceAccount do
include ConnectionHelpers
it 'should query metadata server' do
conn = stub_connection do |stub|
stub.get('/computeMetadata/v1beta1/instance/service-accounts/default/token') do |env|
expect(env.url.host).to eq('metadata')
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/abcdef1234567890",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
end
service_account = Google::APIClient::ComputeServiceAccount.new
auth = service_account.fetch_access_token!({ :connection => conn })
expect(auth).not_to eq(nil?)
expect(auth["access_token"]).to eq("1/abcdef1234567890")
conn.verify
end
end
-618
View File
@@ -1,618 +0,0 @@
# encoding:utf-8
# Copyright 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
require 'google/api_client/service'
fixtures_path = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient::Service do
include ConnectionHelpers
APPLICATION_NAME = 'API Client Tests'
it 'should error out when called without an API name or version' do
expect(lambda do
Google::APIClient::Service.new
end).to raise_error(ArgumentError)
end
it 'should error out when called without an API version' do
expect(lambda do
Google::APIClient::Service.new('foo')
end).to raise_error(ArgumentError)
end
it 'should error out when the options hash is not a hash' do
expect(lambda do
Google::APIClient::Service.new('foo', 'v1', 42)
end).to raise_error(ArgumentError)
end
describe 'with the AdSense Management API' do
it 'should make a valid call for a method with no parameters' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/adclients') do |env|
[200, {}, '{}']
end
end
adsense = Google::APIClient::Service.new(
'adsense',
'v1.3',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = adsense.adclients.list.execute()
conn.verify
end
it 'should make a valid call for a method with parameters' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/adclients/1/adunits') do |env|
[200, {}, '{}']
end
end
adsense = Google::APIClient::Service.new(
'adsense',
'v1.3',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = adsense.adunits.list(:adClientId => '1').execute()
end
it 'should make a valid call for a deep method' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/accounts/1/adclients') do |env|
[200, {}, '{}']
end
end
adsense = Google::APIClient::Service.new(
'adsense',
'v1.3',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = adsense.accounts.adclients.list(:accountId => '1').execute()
end
describe 'with no connection' do
before do
@adsense = Google::APIClient::Service.new('adsense', 'v1.3',
{:application_name => APPLICATION_NAME, :cache_store => nil})
end
it 'should return a resource when using a valid resource name' do
expect(@adsense.accounts).to be_a(Google::APIClient::Service::Resource)
end
it 'should throw an error when using an invalid resource name' do
expect(lambda do
@adsense.invalid_resource
end).to raise_error
end
it 'should return a request when using a valid method name' do
req = @adsense.adclients.list
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('adsense.adclients.list')
expect(req.parameters).to be_nil
end
it 'should throw an error when using an invalid method name' do
expect(lambda do
@adsense.adclients.invalid_method
end).to raise_error
end
it 'should return a valid request with parameters' do
req = @adsense.adunits.list(:adClientId => '1')
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('adsense.adunits.list')
expect(req.parameters).not_to be_nil
expect(req.parameters[:adClientId]).to eq('1')
end
end
end
describe 'with the Prediction API' do
it 'should make a valid call with an object body' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.5/trainedmodels?project=1') do |env|
expect(env.body).to eq('{"id":"1"}')
[200, {}, '{}']
end
end
prediction = Google::APIClient::Service.new(
'prediction',
'v1.5',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = prediction.trainedmodels.insert(:project => '1').body({'id' => '1'}).execute()
conn.verify
end
it 'should make a valid call with a text body' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.5/trainedmodels?project=1') do |env|
expect(env.body).to eq('{"id":"1"}')
[200, {}, '{}']
end
end
prediction = Google::APIClient::Service.new(
'prediction',
'v1.5',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = prediction.trainedmodels.insert(:project => '1').body('{"id":"1"}').execute()
conn.verify
end
describe 'with no connection' do
before do
@prediction = Google::APIClient::Service.new('prediction', 'v1.5',
{:application_name => APPLICATION_NAME, :cache_store => nil})
end
it 'should return a valid request with a body' do
req = @prediction.trainedmodels.insert(:project => '1').body({'id' => '1'})
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('prediction.trainedmodels.insert')
expect(req.body).to eq({'id' => '1'})
expect(req.parameters).not_to be_nil
expect(req.parameters[:project]).to eq('1')
end
it 'should return a valid request with a body when using resource name' do
req = @prediction.trainedmodels.insert(:project => '1').training({'id' => '1'})
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('prediction.trainedmodels.insert')
expect(req.training).to eq({'id' => '1'})
expect(req.parameters).not_to be_nil
expect(req.parameters[:project]).to eq('1')
end
end
end
describe 'with the Drive API' do
before do
@metadata = {
'title' => 'My movie',
'description' => 'The best home movie ever made'
}
@file = File.expand_path('files/sample.txt', fixtures_path)
@media = Google::APIClient::UploadIO.new(@file, 'text/plain')
end
it 'should make a valid call with an object body and media upload' do
conn = stub_connection do |stub|
stub.post('/upload/drive/v1/files?uploadType=multipart') do |env|
expect(env.body).to be_a Faraday::CompositeReadIO
[200, {}, '{}']
end
end
drive = Google::APIClient::Service.new(
'drive',
'v1',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = drive.files.insert(:uploadType => 'multipart').body(@metadata).media(@media).execute()
conn.verify
end
describe 'with no connection' do
before do
@drive = Google::APIClient::Service.new('drive', 'v1',
{:application_name => APPLICATION_NAME, :cache_store => nil})
end
it 'should return a valid request with a body and media upload' do
req = @drive.files.insert(:uploadType => 'multipart').body(@metadata).media(@media)
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('drive.files.insert')
expect(req.body).to eq(@metadata)
expect(req.media).to eq(@media)
expect(req.parameters).not_to be_nil
expect(req.parameters[:uploadType]).to eq('multipart')
end
it 'should return a valid request with a body and media upload when using resource name' do
req = @drive.files.insert(:uploadType => 'multipart').file(@metadata).media(@media)
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('drive.files.insert')
expect(req.file).to eq(@metadata)
expect(req.media).to eq(@media)
expect(req.parameters).not_to be_nil
expect(req.parameters[:uploadType]).to eq('multipart')
end
end
end
describe 'with the Discovery API' do
it 'should make a valid end-to-end request' do
discovery = Google::APIClient::Service.new('discovery', 'v1',
{:application_name => APPLICATION_NAME, :authenticated => false,
:cache_store => nil})
result = discovery.apis.get_rest(:api => 'discovery', :version => 'v1').execute
expect(result).not_to be_nil
expect(result.data.name).to eq('discovery')
expect(result.data.version).to eq('v1')
end
end
end
RSpec.describe Google::APIClient::Service::Result do
describe 'with the plus API' do
before do
@plus = Google::APIClient::Service.new('plus', 'v1',
{:application_name => APPLICATION_NAME, :cache_store => nil})
@reference = Google::APIClient::Reference.new({
:api_method => @plus.activities.list.method,
:parameters => {
'userId' => 'me',
'collection' => 'public',
'maxResults' => 20
}
})
@request = @plus.activities.list(:userId => 'me', :collection => 'public',
:maxResults => 20)
# Response double
@response = double("response")
allow(@response).to receive(:status).and_return(200)
allow(@response).to receive(:headers).and_return({
'etag' => '12345',
'x-google-apiary-auth-scopes' =>
'https://www.googleapis.com/auth/plus.me',
'content-type' => 'application/json; charset=UTF-8',
'date' => 'Mon, 23 Apr 2012 00:00:00 GMT',
'cache-control' => 'private, max-age=0, must-revalidate, no-transform',
'server' => 'GSE',
'connection' => 'close'
})
end
describe 'with a next page token' do
before do
@body = <<-END_OF_STRING
{
"kind": "plus#activityFeed",
"etag": "FOO",
"nextPageToken": "NEXT+PAGE+TOKEN",
"selfLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?",
"nextLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?maxResults=20&pageToken=NEXT%2BPAGE%2BTOKEN",
"title": "Plus Public Activity Feed for ",
"updated": "2012-04-23T00:00:00.000Z",
"id": "123456790",
"items": []
}
END_OF_STRING
allow(@response).to receive(:body).and_return(@body)
base_result = Google::APIClient::Result.new(@reference, @response)
@result = Google::APIClient::Service::Result.new(@request, base_result)
end
it 'should indicate a successful response' do
expect(@result.error?).to be_falsey
end
it 'should return the correct next page token' do
expect(@result.next_page_token).to eq('NEXT+PAGE+TOKEN')
end
it 'generate a correct request when calling next_page' do
next_page_request = @result.next_page
expect(next_page_request.parameters).to include('pageToken')
expect(next_page_request.parameters['pageToken']).to eq('NEXT+PAGE+TOKEN')
@request.parameters.each_pair do |param, value|
expect(next_page_request.parameters[param]).to eq(value)
end
end
it 'should return content type correctly' do
expect(@result.media_type).to eq('application/json')
end
it 'should return the body correctly' do
expect(@result.body).to eq(@body)
end
it 'should return the result data correctly' do
expect(@result.data?).to be_truthy
expect(@result.data.class.to_s).to eq(
'Google::APIClient::Schema::Plus::V1::ActivityFeed'
)
expect(@result.data.kind).to eq('plus#activityFeed')
expect(@result.data.etag).to eq('FOO')
expect(@result.data.nextPageToken).to eq('NEXT+PAGE+TOKEN')
expect(@result.data.selfLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?'
)
expect(@result.data.nextLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?' +
'maxResults=20&pageToken=NEXT%2BPAGE%2BTOKEN'
)
expect(@result.data.title).to eq('Plus Public Activity Feed for ')
expect(@result.data.id).to eq("123456790")
expect(@result.data.items).to be_empty
end
end
describe 'without a next page token' do
before do
@body = <<-END_OF_STRING
{
"kind": "plus#activityFeed",
"etag": "FOO",
"selfLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?",
"title": "Plus Public Activity Feed for ",
"updated": "2012-04-23T00:00:00.000Z",
"id": "123456790",
"items": []
}
END_OF_STRING
allow(@response).to receive(:body).and_return(@body)
base_result = Google::APIClient::Result.new(@reference, @response)
@result = Google::APIClient::Service::Result.new(@request, base_result)
end
it 'should not return a next page token' do
expect(@result.next_page_token).to eq(nil)
end
it 'should return content type correctly' do
expect(@result.media_type).to eq('application/json')
end
it 'should return the body correctly' do
expect(@result.body).to eq(@body)
end
it 'should return the result data correctly' do
expect(@result.data?).to be_truthy
expect(@result.data.class.to_s).to eq(
'Google::APIClient::Schema::Plus::V1::ActivityFeed'
)
expect(@result.data.kind).to eq('plus#activityFeed')
expect(@result.data.etag).to eq('FOO')
expect(@result.data.selfLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?'
)
expect(@result.data.title).to eq('Plus Public Activity Feed for ')
expect(@result.data.id).to eq("123456790")
expect(@result.data.items).to be_empty
end
end
describe 'with JSON error response' do
before do
@body = <<-END_OF_STRING
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
END_OF_STRING
allow(@response).to receive(:body).and_return(@body)
allow(@response).to receive(:status).and_return(400)
base_result = Google::APIClient::Result.new(@reference, @response)
@result = Google::APIClient::Service::Result.new(@request, base_result)
end
it 'should return error status correctly' do
expect(@result.error?).to be_truthy
end
it 'should return the correct error message' do
expect(@result.error_message).to eq('Parse Error')
end
it 'should return the body correctly' do
expect(@result.body).to eq(@body)
end
end
describe 'with 204 No Content response' do
before do
allow(@response).to receive(:body).and_return('')
allow(@response).to receive(:status).and_return(204)
allow(@response).to receive(:headers).and_return({})
base_result = Google::APIClient::Result.new(@reference, @response)
@result = Google::APIClient::Service::Result.new(@request, base_result)
end
it 'should indicate no data is available' do
expect(@result.data?).to be_falsey
end
it 'should return nil for data' do
expect(@result.data).to eq(nil)
end
it 'should return nil for media_type' do
expect(@result.media_type).to eq(nil)
end
end
end
end
RSpec.describe Google::APIClient::Service::BatchRequest do
include ConnectionHelpers
context 'with a service connection' do
before do
@conn = stub_connection do |stub|
stub.post('/batch') do |env|
[500, {'Content-Type' => 'application/json'}, '{}']
end
end
@discovery = Google::APIClient::Service.new('discovery', 'v1',
{:application_name => APPLICATION_NAME, :authorization => nil,
:cache_store => nil, :connection => @conn})
@calls = [
@discovery.apis.get_rest(:api => 'plus', :version => 'v1'),
@discovery.apis.get_rest(:api => 'discovery', :version => 'v1')
]
end
it 'should use the service connection' do
batch = @discovery.batch(@calls) do
end
batch.execute
@conn.verify
end
end
describe 'with the discovery API' do
before do
@discovery = Google::APIClient::Service.new('discovery', 'v1',
{:application_name => APPLICATION_NAME, :authorization => nil,
:cache_store => nil})
end
describe 'with two valid requests' do
before do
@calls = [
@discovery.apis.get_rest(:api => 'plus', :version => 'v1'),
@discovery.apis.get_rest(:api => 'discovery', :version => 'v1')
]
end
it 'should execute both when using a global callback' do
block_called = 0
batch = @discovery.batch(@calls) do |result|
block_called += 1
expect(result.status).to eq(200)
end
batch.execute
expect(block_called).to eq(2)
end
it 'should execute both when using individual callbacks' do
call1_returned, call2_returned = false, false
batch = @discovery.batch
batch.add(@calls[0]) do |result|
call1_returned = true
expect(result.status).to eq(200)
expect(result.call_index).to eq(0)
end
batch.add(@calls[1]) do |result|
call2_returned = true
expect(result.status).to eq(200)
expect(result.call_index).to eq(1)
end
batch.execute
expect(call1_returned).to eq(true)
expect(call2_returned).to eq(true)
end
end
describe 'with a valid request and an invalid one' do
before do
@calls = [
@discovery.apis.get_rest(:api => 'plus', :version => 'v1'),
@discovery.apis.get_rest(:api => 'invalid', :version => 'invalid')
]
end
it 'should execute both when using a global callback' do
block_called = 0
batch = @discovery.batch(@calls) do |result|
block_called += 1
if result.call_index == 0
expect(result.status).to eq(200)
else
expect(result.status).to be >= 400
expect(result.status).to be < 500
end
end
batch.execute
expect(block_called).to eq(2)
end
it 'should execute both when using individual callbacks' do
call1_returned, call2_returned = false, false
batch = @discovery.batch
batch.add(@calls[0]) do |result|
call1_returned = true
expect(result.status).to eq(200)
expect(result.call_index).to eq(0)
end
batch.add(@calls[1]) do |result|
call2_returned = true
expect(result.status).to be >= 400
expect(result.status).to be < 500
expect(result.call_index).to eq(1)
end
batch.execute
expect(call1_returned).to eq(true)
expect(call2_returned).to eq(true)
end
end
end
end
@@ -1,133 +0,0 @@
# encoding:utf-8
# Copyright 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client/service/simple_file_store'
RSpec.describe Google::APIClient::Service::SimpleFileStore do
FILE_NAME = 'test.cache'
describe 'with no cache file' do
before(:each) do
File.delete(FILE_NAME) if File.exists?(FILE_NAME)
@cache = Google::APIClient::Service::SimpleFileStore.new(FILE_NAME)
end
it 'should return nil when asked if a key exists' do
expect(@cache.exist?('invalid')).to be_nil
expect(File.exists?(FILE_NAME)).to be_falsey
end
it 'should return nil when asked to read a key' do
expect(@cache.read('invalid')).to be_nil
expect(File.exists?(FILE_NAME)).to be_falsey
end
it 'should return nil when asked to fetch a key' do
expect(@cache.fetch('invalid')).to be_nil
expect(File.exists?(FILE_NAME)).to be_falsey
end
it 'should create a cache file when asked to fetch a key with a default' do
expect(@cache.fetch('new_key') do
'value'
end).to eq('value')
expect(File.exists?(FILE_NAME)).to be_truthy
end
it 'should create a cache file when asked to write a key' do
@cache.write('new_key', 'value')
expect(File.exists?(FILE_NAME)).to be_truthy
end
it 'should return nil when asked to delete a key' do
expect(@cache.delete('invalid')).to be_nil
expect(File.exists?(FILE_NAME)).to be_falsey
end
end
describe 'with an existing cache' do
before(:each) do
File.delete(FILE_NAME) if File.exists?(FILE_NAME)
@cache = Google::APIClient::Service::SimpleFileStore.new(FILE_NAME)
@cache.write('existing_key', 'existing_value')
end
it 'should return true when asked if an existing key exists' do
expect(@cache.exist?('existing_key')).to be_truthy
end
it 'should return false when asked if a nonexistent key exists' do
expect(@cache.exist?('invalid')).to be_falsey
end
it 'should return the value for an existing key when asked to read it' do
expect(@cache.read('existing_key')).to eq('existing_value')
end
it 'should return nil for a nonexistent key when asked to read it' do
expect(@cache.read('invalid')).to be_nil
end
it 'should return the value for an existing key when asked to read it' do
expect(@cache.read('existing_key')).to eq('existing_value')
end
it 'should return nil for a nonexistent key when asked to fetch it' do
expect(@cache.fetch('invalid')).to be_nil
end
it 'should return and save the default value for a nonexistent key when asked to fetch it with a default' do
expect(@cache.fetch('new_key') do
'value'
end).to eq('value')
expect(@cache.read('new_key')).to eq('value')
end
it 'should remove an existing value and return true when asked to delete it' do
expect(@cache.delete('existing_key')).to be_truthy
expect(@cache.read('existing_key')).to be_nil
end
it 'should return false when asked to delete a nonexistent key' do
expect(@cache.delete('invalid')).to be_falsey
end
it 'should convert keys to strings when storing them' do
@cache.write(:symbol_key, 'value')
expect(@cache.read('symbol_key')).to eq('value')
end
it 'should convert keys to strings when reading them' do
expect(@cache.read(:existing_key)).to eq('existing_value')
end
it 'should convert keys to strings when fetching them' do
expect(@cache.fetch(:existing_key)).to eq('existing_value')
end
it 'should convert keys to strings when deleting them' do
expect(@cache.delete(:existing_key)).to be_truthy
expect(@cache.read('existing_key')).to be_nil
end
end
after(:all) do
File.delete(FILE_NAME) if File.exists?(FILE_NAME)
end
end
-352
View File
@@ -1,352 +0,0 @@
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'faraday'
require 'signet/oauth_1/client'
require 'google/api_client'
shared_examples_for 'configurable user agent' do
include ConnectionHelpers
it 'should allow the user agent to be modified' do
client.user_agent = 'Custom User Agent/1.2.3'
expect(client.user_agent).to eq('Custom User Agent/1.2.3')
end
it 'should allow the user agent to be set to nil' do
client.user_agent = nil
expect(client.user_agent).to eq(nil)
end
it 'should not allow the user agent to be used with bogus values' do
expect(lambda do
client.user_agent = 42
client.execute(:uri=>'https://www.google.com/')
end).to raise_error(TypeError)
end
it 'should transmit a User-Agent header when sending requests' do
client.user_agent = 'Custom User Agent/1.2.3'
conn = stub_connection do |stub|
stub.get('/') do |env|
headers = env[:request_headers]
expect(headers).to have_key('User-Agent')
expect(headers['User-Agent']).to eq(client.user_agent)
[200, {}, ['']]
end
end
client.execute(:uri=>'https://www.google.com/', :connection => conn)
conn.verify
end
end
RSpec.describe Google::APIClient do
include ConnectionHelpers
let(:client) { Google::APIClient.new(:application_name => 'API Client Tests') }
it "should pass the faraday options provided on initialization to FaraDay configuration block" do
client = Google::APIClient.new(faraday_option: {timeout: 999})
expect(client.connection.options.timeout).to be == 999
end
it 'should make its version number available' do
expect(Google::APIClient::VERSION::STRING).to be_instance_of(String)
end
it 'should default to OAuth 2' do
expect(Signet::OAuth2::Client).to be === client.authorization
end
describe 'configure for no authentication' do
before do
client.authorization = nil
end
it_should_behave_like 'configurable user agent'
end
describe 'configured for OAuth 1' do
before do
client.authorization = :oauth_1
client.authorization.token_credential_key = 'abc'
client.authorization.token_credential_secret = '123'
end
it 'should use the default OAuth1 client configuration' do
expect(client.authorization.temporary_credential_uri.to_s).to eq(
'https://www.google.com/accounts/OAuthGetRequestToken'
)
expect(client.authorization.authorization_uri.to_s).to include(
'https://www.google.com/accounts/OAuthAuthorizeToken'
)
expect(client.authorization.token_credential_uri.to_s).to eq(
'https://www.google.com/accounts/OAuthGetAccessToken'
)
expect(client.authorization.client_credential_key).to eq('anonymous')
expect(client.authorization.client_credential_secret).to eq('anonymous')
end
it_should_behave_like 'configurable user agent'
end
describe 'configured for OAuth 2' do
before do
client.authorization = :oauth_2
client.authorization.access_token = '12345'
end
# TODO
it_should_behave_like 'configurable user agent'
end
describe 'when executing requests' do
before do
@prediction = client.discovered_api('prediction', 'v1.2')
client.authorization = :oauth_2
@connection = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
expect(env[:request_headers]['Authorization']).to eq('Bearer 12345')
[200, {}, '{}']
end
end
end
after do
@connection.verify
end
it 'should use default authorization' do
client.authorization.access_token = "12345"
client.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => @connection
)
end
it 'should use request scoped authorization when provided' do
client.authorization.access_token = "abcdef"
new_auth = Signet::OAuth2::Client.new(:access_token => '12345')
client.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:authorization => new_auth,
:connection => @connection
)
end
it 'should accept options with batch/request style execute' do
client.authorization.access_token = "abcdef"
new_auth = Signet::OAuth2::Client.new(:access_token => '12345')
request = client.generate_request(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'}
)
client.execute(
request,
:authorization => new_auth,
:connection => @connection
)
end
it 'should accept options in array style execute' do
client.authorization.access_token = "abcdef"
new_auth = Signet::OAuth2::Client.new(:access_token => '12345')
client.execute(
@prediction.training.insert, {'data' => '12345'}, '', {},
{ :authorization => new_auth, :connection => @connection }
)
end
end
describe 'when retries enabled' do
before do
client.retries = 2
end
after do
@connection.verify
end
it 'should follow redirects' do
client.authorization = nil
@connection = stub_connection do |stub|
stub.get('/foo') do |env|
[302, {'location' => 'https://www.google.com/bar'}, '{}']
end
stub.get('/bar') do |env|
[200, {}, '{}']
end
end
client.execute(
:uri => 'https://www.google.com/foo',
:connection => @connection
)
end
it 'should refresh tokens on 401 errors' do
client.authorization.access_token = '12345'
expect(client.authorization).to receive(:fetch_access_token!)
@connection = stub_connection do |stub|
stub.get('/foo') do |env|
[401, {}, '{}']
end
stub.get('/foo') do |env|
[200, {}, '{}']
end
end
client.execute(
:uri => 'https://www.google.com/foo',
:connection => @connection
)
end
it 'should not attempt multiple token refreshes' do
client.authorization.access_token = '12345'
expect(client.authorization).to receive(:fetch_access_token!).once
@connection = stub_connection do |stub|
stub.get('/foo') do |env|
[401, {}, '{}']
end
end
client.execute(
:uri => 'https://www.google.com/foo',
:connection => @connection
)
end
it 'should not retry on client errors' do
count = 0
@connection = stub_connection do |stub|
stub.get('/foo') do |env|
expect(count).to eq(0)
count += 1
[403, {}, '{}']
end
end
client.execute(
:uri => 'https://www.google.com/foo',
:connection => @connection,
:authenticated => false
)
end
it 'should retry on 500 errors' do
client.authorization = nil
@connection = stub_connection do |stub|
stub.get('/foo') do |env|
[500, {}, '{}']
end
stub.get('/foo') do |env|
[200, {}, '{}']
end
end
expect(client.execute(
:uri => 'https://www.google.com/foo',
:connection => @connection
).status).to eq(200)
end
it 'should fail after max retries' do
client.authorization = nil
count = 0
@connection = stub_connection do |stub|
stub.get('/foo') do |env|
count += 1
[500, {}, '{}']
end
end
expect(client.execute(
:uri => 'https://www.google.com/foo',
:connection => @connection
).status).to eq(500)
expect(count).to eq(3)
end
end
describe 'when retries disabled and expired_auth_retry on (default)' do
before do
client.retries = 0
end
after do
@connection.verify
end
it 'should refresh tokens on 401 errors' do
client.authorization.access_token = '12345'
expect(client.authorization).to receive(:fetch_access_token!)
@connection = stub_connection do |stub|
stub.get('/foo') do |env|
[401, {}, '{}']
end
stub.get('/foo') do |env|
[200, {}, '{}']
end
end
client.execute(
:uri => 'https://www.gogole.com/foo',
:connection => @connection
)
end
end
describe 'when retries disabled and expired_auth_retry off' do
before do
client.retries = 0
client.expired_auth_retry = false
end
it 'should not refresh tokens on 401 errors' do
client.authorization.access_token = '12345'
expect(client.authorization).not_to receive(:fetch_access_token!)
@connection = stub_connection do |stub|
stub.get('/foo') do |env|
[401, {}, '{}']
end
stub.get('/foo') do |env|
[200, {}, '{}']
end
end
resp = client.execute(
:uri => 'https://www.gogole.com/foo',
:connection => @connection
)
expect(resp.response.status).to be == 401
end
end
end
-66
View File
@@ -1,66 +0,0 @@
$LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__))
$LOAD_PATH.uniq!
require 'rspec'
require 'faraday'
begin
require 'simplecov'
require 'coveralls'
SimpleCov.formatter = Coveralls::SimpleCov::Formatter
SimpleCov.start
rescue LoadError
# SimpleCov missing, so just run specs with no coverage.
end
Faraday::Adapter.load_middleware(:test)
module Faraday
class Connection
def verify
if app.kind_of?(Faraday::Adapter::Test)
app.stubs.verify_stubbed_calls
else
raise TypeError, "Expected test adapter"
end
end
end
end
module ConnectionHelpers
def stub_connection(&block)
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
block.call(stub)
end
connection = Faraday.new do |builder|
builder.options.params_encoder = Faraday::FlatParamsEncoder
builder.adapter(:test, stubs)
end
end
end
module JSONMatchers
class EqualsJson
def initialize(expected)
@expected = JSON.parse(expected)
end
def matches?(target)
@target = JSON.parse(target)
@target.eql?(@expected)
end
def failure_message
"expected #{@target.inspect} to be #{@expected}"
end
def negative_failure_message
"expected #{@target.inspect} not to be #{@expected}"
end
end
def be_json(expected)
EqualsJson.new(expected)
end
end
RSpec.configure do |config|
end