Skip to content

Instantly share code, notes, and snippets.

@jimbaker
Last active November 15, 2016 15:29
Show Gist options
  • Save jimbaker/df47cabfefa6d6985af9029449b589df to your computer and use it in GitHub Desktop.
Save jimbaker/df47cabfefa6d6985af9029449b589df to your computer and use it in GitHub Desktop.
Some basic testing of cratonclient
from __future__ import print_function
from ipaddress import ip_address
# Ideally we have some __init__ support to reduce different import locations
from cratonclient.session import Session
from cratonclient.v1.client import Client as CratonClient
from cratonclient.v1.hosts import HostManager
# useful to generate some inventory with
# $ python tools/generate_fake_data.py --url http://127.0.0.1:8080/v1 --user demo --project $UUID --key demo
# following the comments in Craton's Dockerfile
def verify_hosts(hosts, num_ips):
# given some hosts, verify we have all the ip addresses generated by the fake data script
start_ip_address = ip_address(u'192.168.1.5')
expected_ip_addresses = {str(start_ip_address + i) for i in range(num_ips)}
#expected_ip_addresses.add('10.10.1.1')
print("expected", expected_ip_addresses)
print("actual", {host.ip_address for host in hosts})
return expected_ip_addresses == {host.ip_address for host in hosts}
# IDs can be strings or ints; using defaults from Dockerfile
session = Session(username='demo', token='demo', project_id='b9f10eca66ac4c279c139d01e65f96b4')
url = 'http://127.0.0.1:8080'
craton = CratonClient(session, url)
# use of high level API - generates this request: "GET /v1/hosts?region=1"
inventory = craton.inventory(1) # region_id is currently ignored in terms of setting context
# requires fix that this is region_id, not project_id; presumably
# should be implied by above context - I would imagine list actually
# takes **kwargs to specify the filtering
hosts = inventory.hosts.list(region_id=2)
ip_addresses = {host.ip_address for host in hosts}
print(hosts) # minor - perhaps would be nice if Host is default sortable, say on ip_address
print('verified all hosts in region:', verify_hosts(hosts, 8))
# use of low level API - note this generates this request:
# "GET /hosts?region=1" without the change to the URL below
hosts_mgr = HostManager(1, session, url + "/v1")
hosts = hosts_mgr.list()
print(hosts)
print('verified all hosts in region:', verify_hosts(hosts, 8))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment