Skip to content

Instantly share code, notes, and snippets.

@akdh
Last active September 8, 2015 23:12
Show Gist options
  • Save akdh/564cbb5f9c6c92c99d8a to your computer and use it in GitHub Desktop.
Save akdh/564cbb5f9c6c92c99d8a to your computer and use it in GitHub Desktop.
Validation testing instructions for suggestion services.

Test your service

See https://github.com/akdh/cst-tools for JSON schemas.

Assuming your service callback URL is http://127.0.0.1:5002/suggestions, you can make a request to your service and ensure that it is valid using the following commands:

curl -H "Content-Type: application/json" --data @request.json -XPOST http://127.0.0.1:5002/suggestions > response.json
python validate.py data.json 192

No errors should be produced.

Note that you must have docs.db in the same directory as validate.py.

{"location": {"lng": -85.6681, "state": "MI", "id": 192, "lat": 42.9634, "name": "Grand Rapids"}, "person": {"preferences": [{"documentId": "TRECCS-00070139-234", "rating": 4, "tags": ["Food & Drink"]}, {"documentId": "TRECCS-00070147-234", "rating": 1}], "id": 1}, "duration": "Longer", "season": "Spring", "group": "Friends"}
{
"suggestions": [
"TRECCS-00091446-192",
"TRECCS-00092282-192",
"TRECCS-00091195-192",
"TRECCS-00352184-192",
"TRECCS-00092237-192",
"TRECCS-01438958-192",
"TRECCS-00091306-192",
"TRECCS-00838036-192",
"TRECCS-00352821-192",
"TRECCS-01438558-192"
]
}
import sqlite3, json, sys
import jsonschema
def validate(data, location = None, db_filename = 'docs.db', schema_filename = 'response_schema.json'):
with open(schema_filename) as f:
schema = json.loads(f.read())
jsonschema.validate(data, schema)
conn = sqlite3.connect(db_filename)
cur = conn.cursor()
for id in data['suggestions']:
cur.execute('select location from docs where id = ?', (id, ))
row = cur.fetchone()
if row is None:
raise ValueError('ID is not a valid attraction', id)
if location and row[0] != int(location):
raise ValueError('Attraction ID does not correspond to location', id, location)
conn.close()
if __name__ == '__main__':
if len(sys.argv) <= 1:
print("usage: %s DATA [LOCATION]")
exit()
data_filename = sys.argv[1]
with open(data_filename) as f:
data = json.loads(f.read())
location_id = None
if len(sys.argv) == 3:
location_id = sys.argv[2]
validate(data, location_id)
print('Valid')
@feay1234
Copy link

feay1234 commented Jun 3, 2015

In line 7 in response_schema.json, should the item's type be string, instead of number?

Tried to change to string and it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment